summaryrefslogtreecommitdiffstats
path: root/Lib/heapq.py
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2008-12-31 04:18:44 (GMT)
committerRaymond Hettinger <python@rcn.com>2008-12-31 04:18:44 (GMT)
commitd263bd8d4a2f6dbe30b8562eed1521562a370ce0 (patch)
tree86f5a7a132e60b4012d508794f1faca563a59809 /Lib/heapq.py
parente4ea6bc9f365d402faa699680500c99b08c1e26e (diff)
downloadcpython-d263bd8d4a2f6dbe30b8562eed1521562a370ce0.zip
cpython-d263bd8d4a2f6dbe30b8562eed1521562a370ce0.tar.gz
cpython-d263bd8d4a2f6dbe30b8562eed1521562a370ce0.tar.bz2
Issue 4790: Eliminate unnecessary work from heapq's nlargest() and nsmallest()
functions for the common case where no key function is specified.
Diffstat (limited to 'Lib/heapq.py')
-rw-r--r--Lib/heapq.py8
1 files changed, 8 insertions, 0 deletions
diff --git a/Lib/heapq.py b/Lib/heapq.py
index 0a83b76..c13d650 100644
--- a/Lib/heapq.py
+++ b/Lib/heapq.py
@@ -354,6 +354,10 @@ def nsmallest(n, iterable, key=None):
Equivalent to: sorted(iterable, key=key)[:n]
"""
+ if key is None:
+ it = izip(iterable, count()) # decorate
+ result = _nsmallest(n, it)
+ return map(itemgetter(0), result) # undecorate
in1, in2 = tee(iterable)
it = izip(imap(key, in1), count(), in2) # decorate
result = _nsmallest(n, it)
@@ -365,6 +369,10 @@ def nlargest(n, iterable, key=None):
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
"""
+ if key is None:
+ it = izip(iterable, imap(neg, count())) # decorate
+ result = _nlargest(n, it)
+ return map(itemgetter(0), result) # undecorate
in1, in2 = tee(iterable)
it = izip(imap(key, in1), imap(neg, count()), in2) # decorate
result = _nlargest(n, it)