]> granicus.if.org Git - python/commitdiff
Issue 4790: Eliminate unnecessary work from heapq's nlargest() and nsmallest()
authorRaymond Hettinger <python@rcn.com>
Wed, 31 Dec 2008 04:18:44 +0000 (04:18 +0000)
committerRaymond Hettinger <python@rcn.com>
Wed, 31 Dec 2008 04:18:44 +0000 (04:18 +0000)
functions for the common case where no key function is specified.

Lib/heapq.py
Misc/NEWS

index 0a83b76b464d1db250ea8172fc4ed17ab9ef54e2..c13d6500b6e44d8759f186f64c7540ebc096a9c5 100644 (file)
@@ -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)
index 885bbb2a79b8ba016fe47e72be038b60806f4295..9bdd262a5fb1d9d29c55c72d9bb395588caa6475 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -44,6 +44,9 @@ Core and Builtins
 Library
 -------
 
+- Issue 4790: The nsmallest() and nlargest() functions in the heapq module
+  did unnecessary work in the common case where no key function was specified.
+
 - Issue #3767: Convert Tk object to string in tkColorChooser.
 
 - Issue #3248: Allow placing ScrolledText in a PanedWindow.