[Python-checkins] r68095 - in python/branches/release26-maint: Lib/heapq.py Misc/NEWS

raymond.hettinger python-checkins at python.org
Wed Dec 31 05:18:44 CET 2008


Author: raymond.hettinger
Date: Wed Dec 31 05:18:44 2008
New Revision: 68095

Log:
Issue 4790:  Eliminate unnecessary work from heapq's nlargest() and nsmallest()
functions for the common case where no key function is specified.



Modified:
   python/branches/release26-maint/Lib/heapq.py
   python/branches/release26-maint/Misc/NEWS

Modified: python/branches/release26-maint/Lib/heapq.py
==============================================================================
--- python/branches/release26-maint/Lib/heapq.py	(original)
+++ python/branches/release26-maint/Lib/heapq.py	Wed Dec 31 05:18:44 2008
@@ -354,6 +354,10 @@
 
     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 @@
 
     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)

Modified: python/branches/release26-maint/Misc/NEWS
==============================================================================
--- python/branches/release26-maint/Misc/NEWS	(original)
+++ python/branches/release26-maint/Misc/NEWS	Wed Dec 31 05:18:44 2008
@@ -44,6 +44,9 @@
 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.


More information about the Python-checkins mailing list