Issue 13274: Make the pure python code for heapq more closely match the C implementation for an undefined corner case.

This commit is contained in:
Raymond Hettinger 2011-10-30 14:29:06 -07:00
parent 6361ea2b07
commit e11a47e207
1 changed files with 4 additions and 0 deletions

View File

@ -193,6 +193,8 @@ def nlargest(n, iterable):
Equivalent to: sorted(iterable, reverse=True)[:n]
"""
if n < 0:
return []
it = iter(iterable)
result = list(islice(it, n))
if not result:
@ -209,6 +211,8 @@ def nsmallest(n, iterable):
Equivalent to: sorted(iterable)[:n]
"""
if n < 0:
return []
if hasattr(iterable, '__len__') and n * 10 <= len(iterable):
# For smaller values of n, the bisect method is faster than a minheap.
# It is also memory efficient, consuming only n elements of space.