Issue 4790: Eliminate unnecessary work from heapq's nlargest() and nsmallest()

functions for the common case where no key function is specified.
This commit is contained in:
Raymond Hettinger 2008-12-31 04:18:44 +00:00
parent e4ea6bc9f3
commit d263bd8d4a
2 changed files with 11 additions and 0 deletions

View 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)

View File

@ -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.