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

Lib/heapq.py
Misc/NEWS

index 380fe1268bf834189a49aeb675d06ff4ed835401..2d3404644aa4db308213f816c416f1fa95be1639 100644 (file)
@@ -354,9 +354,12 @@ def nsmallest(n, iterable, key=None):
 
     Equivalent to:  sorted(iterable, key=key)[:n]
     """
+    if key is None:
+        it = zip(iterable, count())                         # decorate
+        result = _nsmallest(n, it)
+        return list(map(itemgetter(0), result))             # undecorate
     in1, in2 = tee(iterable)
-    keys = in1 if key is None else map(key, in1)
-    it = zip(keys, count(), in2)                           # decorate
+    it = zip(map(key, in1), count(), in2)                   # decorate
     result = _nsmallest(n, it)
     return list(map(itemgetter(2), result))                 # undecorate
 
@@ -366,9 +369,12 @@ def nlargest(n, iterable, key=None):
 
     Equivalent to:  sorted(iterable, key=key, reverse=True)[:n]
     """
+    if key is None:
+        it = zip(iterable, map(neg, count()))               # decorate
+        result = _nlargest(n, it)
+        return list(map(itemgetter(0), result))             # undecorate
     in1, in2 = tee(iterable)
-    keys = in1 if key is None else map(key, in1)
-    it = zip(keys, map(neg, count()), in2)                 # decorate
+    it = zip(map(key, in1), map(neg, count()), in2)         # decorate
     result = _nlargest(n, it)
     return list(map(itemgetter(2), result))                 # undecorate
 
index 634fc91eb360bb5177267b0eeeb44e8f4ece740c..7c8a79377791d9f4aec6c4a1f87aceecb2640dbb 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -45,6 +45,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 #4702: Throwing a DistutilsPlatformError instead of IOError in case 
   no MSVC compiler is found under Windows. Original patch by Philip Jenvey.