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

raymond.hettinger python-checkins at python.org
Wed Dec 31 05:33:06 CET 2008


Author: raymond.hettinger
Date: Wed Dec 31 05:33:06 2008
New Revision: 68096
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/release30-maint/Lib/heapq.py
 python/branches/release30-maint/Misc/NEWS
Modified: python/branches/release30-maint/Lib/heapq.py
==============================================================================
--- python/branches/release30-maint/Lib/heapq.py	(original)
+++ python/branches/release30-maint/Lib/heapq.py	Wed Dec 31 05:33:06 2008
@@ -354,9 +354,12 @@
 
 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 @@
 
 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
 
Modified: python/branches/release30-maint/Misc/NEWS
==============================================================================
--- python/branches/release30-maint/Misc/NEWS	(original)
+++ python/branches/release30-maint/Misc/NEWS	Wed Dec 31 05:33:06 2008
@@ -45,6 +45,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 #4702: Throwing a DistutilsPlatformError instead of IOError in case 
 no MSVC compiler is found under Windows. Original patch by Philip Jenvey. 
 


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /