From d263bd8d4a2f6dbe30b8562eed1521562a370ce0 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Wed, 31 Dec 2008 04:18:44 +0000 Subject: [PATCH] Issue 4790: Eliminate unnecessary work from heapq's nlargest() and nsmallest() functions for the common case where no key function is specified. --- Lib/heapq.py | 8 ++++++++ Misc/NEWS | 3 +++ 2 files changed, 11 insertions(+) diff --git a/Lib/heapq.py b/Lib/heapq.py index 0a83b76b46..c13d6500b6 100644 --- a/Lib/heapq.py +++ b/Lib/heapq.py @@ -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) diff --git a/Misc/NEWS b/Misc/NEWS index 885bbb2a79..9bdd262a5f 100644 --- 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. -- 2.49.0