Simplify the nlargest() code using heappushpop().

This commit is contained in:
Raymond Hettinger 2008-03-13 19:33:34 +00:00
parent 53bdf09343
commit 83aa6a3b1a
1 changed files with 2 additions and 6 deletions

View File

@ -193,13 +193,9 @@ def nlargest(n, iterable):
if not result: if not result:
return result return result
heapify(result) heapify(result)
_heapreplace = heapreplace _heappushpop = heappushpop
sol = result[0] # sol --> smallest of the nlargest
for elem in it: for elem in it:
if elem <= sol: heappushpop(result, elem)
continue
_heapreplace(result, elem)
sol = result[0]
result.sort(reverse=True) result.sort(reverse=True)
return result return result