blob: 41626c56a73abe85fdbf1ea9a96adaebf359bee1 [file] [log] [blame]
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +00001"""Heap queue algorithm (a.k.a. priority queue).
2
3Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
4all k, counting elements from 0. For the sake of comparison,
5non-existing elements are considered to be infinite. The interesting
6property of a heap is that a[0] is always its smallest element.
7
8Usage:
9
10heap = [] # creates an empty heap
11heappush(heap, item) # pushes a new item on the heap
12item = heappop(heap) # pops the smallest item from the heap
13item = heap[0] # smallest item on the heap without popping it
14heapify(x) # transforms list into a heap, in-place, in linear time
15item = heapreplace(heap, item) # pops and returns smallest item, and adds
16 # new item; the heap size is unchanged
17
18Our API differs from textbook heap algorithms as follows:
19
20- We use 0-based indexing. This makes the relationship between the
21 index for a node and the indexes for its children slightly less
22 obvious, but is more suitable since Python uses 0-based indexing.
23
24- Our heappop() method returns the smallest item, not the largest.
25
26These two make it possible to view the heap as a regular Python list
27without surprises: heap[0] is the smallest item, and heap.sort()
28maintains the heap invariant!
29"""
30
Raymond Hettinger33ecffb2004-06-10 05:03:17 +000031# Original code by Kevin O'Connor, augmented by Tim Peters and Raymond Hettinger
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000032
33__about__ = """Heap queues
34
Mark Dickinsonb4a17a82010-07-04 19:23:49 +000035[explanation by François Pinard]
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000036
37Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
38all k, counting elements from 0. For the sake of comparison,
39non-existing elements are considered to be infinite. The interesting
40property of a heap is that a[0] is always its smallest element.
41
42The strange invariant above is meant to be an efficient memory
43representation for a tournament. The numbers below are `k', not a[k]:
44
45 0
46
47 1 2
48
49 3 4 5 6
50
51 7 8 9 10 11 12 13 14
52
53 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
54
55
56In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In
57an usual binary tournament we see in sports, each cell is the winner
58over the two cells it tops, and we can trace the winner down the tree
59to see all opponents s/he had. However, in many computer applications
60of such tournaments, we do not need to trace the history of a winner.
61To be more memory efficient, when a winner is promoted, we try to
62replace it by something else at a lower level, and the rule becomes
63that a cell and the two cells it tops contain three different items,
64but the top cell "wins" over the two topped cells.
65
66If this heap invariant is protected at all time, index 0 is clearly
67the overall winner. The simplest algorithmic way to remove it and
68find the "next" winner is to move some loser (let's say cell 30 in the
69diagram above) into the 0 position, and then percolate this new 0 down
70the tree, exchanging values, until the invariant is re-established.
71This is clearly logarithmic on the total number of items in the tree.
72By iterating over all items, you get an O(n ln n) sort.
73
74A nice feature of this sort is that you can efficiently insert new
75items while the sort is going on, provided that the inserted items are
76not "better" than the last 0'th element you extracted. This is
77especially useful in simulation contexts, where the tree holds all
78incoming events, and the "win" condition means the smallest scheduled
79time. When an event schedule other events for execution, they are
80scheduled into the future, so they can easily go into the heap. So, a
81heap is a good structure for implementing schedulers (this is what I
82used for my MIDI sequencer :-).
83
84Various structures for implementing schedulers have been extensively
85studied, and heaps are good for this, as they are reasonably speedy,
86the speed is almost constant, and the worst case is not much different
87than the average case. However, there are other representations which
88are more efficient overall, yet the worst cases might be terrible.
89
90Heaps are also very useful in big disk sorts. You most probably all
91know that a big sort implies producing "runs" (which are pre-sorted
92sequences, which size is usually related to the amount of CPU memory),
93followed by a merging passes for these runs, which merging is often
94very cleverly organised[1]. It is very important that the initial
95sort produces the longest runs possible. Tournaments are a good way
96to that. If, using all the memory available to hold a tournament, you
97replace and percolate items that happen to fit the current run, you'll
98produce runs which are twice the size of the memory for random input,
99and much better for input fuzzily ordered.
100
101Moreover, if you output the 0'th item on disk and get an input which
102may not fit in the current tournament (because the value "wins" over
103the last output value), it cannot fit in the heap, so the size of the
104heap decreases. The freed memory could be cleverly reused immediately
105for progressively building a second heap, which grows at exactly the
106same rate the first heap is melting. When the first heap completely
107vanishes, you switch heaps and start a new run. Clever and quite
108effective!
109
110In a word, heaps are useful memory structures to know. I use them in
111a few applications, and I think it is good to keep a `heap' module
112around. :-)
113
114--------------------
115[1] The disk balancing algorithms which are current, nowadays, are
116more annoying than clever, and this is a consequence of the seeking
117capabilities of the disks. On devices which cannot seek, like big
118tape drives, the story was quite different, and one had to be very
119clever to ensure (far in advance) that each tape movement will be the
120most effective possible (that is, will best participate at
121"progressing" the merge). Some tapes were even able to read
122backwards, and this was also used to avoid the rewinding time.
123Believe me, real good tape sorts were quite spectacular to watch!
124From all times, sorting has always been a Great Art! :-)
125"""
126
Thomas Wouterscf297e42007-02-23 15:07:44 +0000127__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000128 'nlargest', 'nsmallest', 'heappushpop']
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000129
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700130from itertools import islice, count
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000131
132def heappush(heap, item):
133 """Push item onto heap, maintaining the heap invariant."""
134 heap.append(item)
135 _siftdown(heap, 0, len(heap)-1)
136
137def heappop(heap):
138 """Pop the smallest item off the heap, maintaining the heap invariant."""
139 lastelt = heap.pop() # raises appropriate IndexError if heap is empty
140 if heap:
141 returnitem = heap[0]
142 heap[0] = lastelt
143 _siftup(heap, 0)
Raymond Hettinger356902d2014-05-19 22:13:45 +0100144 return returnitem
145 return lastelt
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000146
147def heapreplace(heap, item):
148 """Pop and return the current smallest value, and add the new item.
149
150 This is more efficient than heappop() followed by heappush(), and can be
151 more appropriate when using a fixed-size heap. Note that the value
152 returned may be larger than item! That constrains reasonable uses of
Raymond Hettinger8158e842004-09-06 07:04:09 +0000153 this routine unless written as part of a conditional replacement:
Raymond Hettinger28224f82004-06-20 09:07:53 +0000154
Raymond Hettinger8158e842004-09-06 07:04:09 +0000155 if item > heap[0]:
156 item = heapreplace(heap, item)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000157 """
158 returnitem = heap[0] # raises appropriate IndexError if heap is empty
159 heap[0] = item
160 _siftup(heap, 0)
161 return returnitem
162
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000163def heappushpop(heap, item):
164 """Fast version of a heappush followed by a heappop."""
Georg Brandlf78e02b2008-06-10 17:40:04 +0000165 if heap and heap[0] < item:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000166 item, heap[0] = heap[0], item
167 _siftup(heap, 0)
168 return item
169
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000170def heapify(x):
Éric Araujo395ba352011-04-15 23:34:31 +0200171 """Transform list into a heap, in-place, in O(len(x)) time."""
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000172 n = len(x)
173 # Transform bottom-up. The largest index there's any point to looking at
174 # is the largest with a child index in-range, so must have 2*i + 1 < n,
175 # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
176 # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is
177 # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
Guido van Rossum805365e2007-05-07 22:24:25 +0000178 for i in reversed(range(n//2)):
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000179 _siftup(x, i)
180
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700181def _heapreplace_max(heap, item):
182 """Maxheap version of a heappop followed by a heappush."""
183 returnitem = heap[0] # raises appropriate IndexError if heap is empty
184 heap[0] = item
185 _siftup_max(heap, 0)
186 return returnitem
Raymond Hettingerf6b26672013-03-05 01:36:30 -0500187
188def _heapify_max(x):
189 """Transform list into a maxheap, in-place, in O(len(x)) time."""
190 n = len(x)
191 for i in reversed(range(n//2)):
192 _siftup_max(x, i)
193
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000194# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos
195# is the index of a leaf with a possibly out-of-order value. Restore the
196# heap invariant.
197def _siftdown(heap, startpos, pos):
198 newitem = heap[pos]
199 # Follow the path to the root, moving parents down until finding a place
200 # newitem fits.
201 while pos > startpos:
202 parentpos = (pos - 1) >> 1
203 parent = heap[parentpos]
Georg Brandlf78e02b2008-06-10 17:40:04 +0000204 if newitem < parent:
205 heap[pos] = parent
206 pos = parentpos
207 continue
208 break
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000209 heap[pos] = newitem
210
211# The child indices of heap index pos are already heaps, and we want to make
212# a heap at index pos too. We do this by bubbling the smaller child of
213# pos up (and so on with that child's children, etc) until hitting a leaf,
214# then using _siftdown to move the oddball originally at index pos into place.
215#
216# We *could* break out of the loop as soon as we find a pos where newitem <=
217# both its children, but turns out that's not a good idea, and despite that
218# many books write the algorithm that way. During a heap pop, the last array
219# element is sifted in, and that tends to be large, so that comparing it
220# against values starting from the root usually doesn't pay (= usually doesn't
221# get us out of the loop early). See Knuth, Volume 3, where this is
222# explained and quantified in an exercise.
223#
224# Cutting the # of comparisons is important, since these routines have no
225# way to extract "the priority" from an array element, so that intelligence
Mark Dickinsona56c4672009-01-27 18:17:45 +0000226# is likely to be hiding in custom comparison methods, or in array elements
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000227# storing (priority, record) tuples. Comparisons are thus potentially
228# expensive.
229#
230# On random arrays of length 1000, making this change cut the number of
231# comparisons made by heapify() a little, and those made by exhaustive
232# heappop() a lot, in accord with theory. Here are typical results from 3
233# runs (3 just to demonstrate how small the variance is):
234#
235# Compares needed by heapify Compares needed by 1000 heappops
236# -------------------------- --------------------------------
237# 1837 cut to 1663 14996 cut to 8680
238# 1855 cut to 1659 14966 cut to 8678
239# 1847 cut to 1660 15024 cut to 8703
240#
241# Building the heap by using heappush() 1000 times instead required
242# 2198, 2148, and 2219 compares: heapify() is more efficient, when
243# you can use it.
244#
245# The total compares needed by list.sort() on the same lists were 8627,
246# 8627, and 8632 (this should be compared to the sum of heapify() and
247# heappop() compares): list.sort() is (unsurprisingly!) more efficient
248# for sorting.
249
250def _siftup(heap, pos):
251 endpos = len(heap)
252 startpos = pos
253 newitem = heap[pos]
254 # Bubble up the smaller child until hitting a leaf.
255 childpos = 2*pos + 1 # leftmost child position
256 while childpos < endpos:
257 # Set childpos to index of smaller child.
258 rightpos = childpos + 1
Georg Brandlf78e02b2008-06-10 17:40:04 +0000259 if rightpos < endpos and not heap[childpos] < heap[rightpos]:
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000260 childpos = rightpos
261 # Move the smaller child up.
262 heap[pos] = heap[childpos]
263 pos = childpos
264 childpos = 2*pos + 1
265 # The leaf at pos is empty now. Put newitem there, and bubble it up
266 # to its final resting place (by sifting its parents down).
267 heap[pos] = newitem
268 _siftdown(heap, startpos, pos)
269
Raymond Hettingerf6b26672013-03-05 01:36:30 -0500270def _siftdown_max(heap, startpos, pos):
271 'Maxheap variant of _siftdown'
272 newitem = heap[pos]
273 # Follow the path to the root, moving parents down until finding a place
274 # newitem fits.
275 while pos > startpos:
276 parentpos = (pos - 1) >> 1
277 parent = heap[parentpos]
278 if parent < newitem:
279 heap[pos] = parent
280 pos = parentpos
281 continue
282 break
283 heap[pos] = newitem
284
285def _siftup_max(heap, pos):
Raymond Hettinger2e8d9a72013-03-05 02:11:10 -0500286 'Maxheap variant of _siftup'
Raymond Hettingerf6b26672013-03-05 01:36:30 -0500287 endpos = len(heap)
288 startpos = pos
289 newitem = heap[pos]
290 # Bubble up the larger child until hitting a leaf.
291 childpos = 2*pos + 1 # leftmost child position
292 while childpos < endpos:
293 # Set childpos to index of larger child.
294 rightpos = childpos + 1
295 if rightpos < endpos and not heap[rightpos] < heap[childpos]:
296 childpos = rightpos
297 # Move the larger child up.
298 heap[pos] = heap[childpos]
299 pos = childpos
300 childpos = 2*pos + 1
301 # The leaf at pos is empty now. Put newitem there, and bubble it up
302 # to its final resting place (by sifting its parents down).
303 heap[pos] = newitem
304 _siftdown_max(heap, startpos, pos)
305
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000306# If available, use C implementation
307try:
Raymond Hettinger0dd737b2009-03-29 19:30:50 +0000308 from _heapq import *
Brett Cannoncd171c82013-07-04 17:43:24 -0400309except ImportError:
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000310 pass
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700311try:
312 from _heapq import _heapreplace_max
313except ImportError:
314 pass
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000315
Thomas Wouterscf297e42007-02-23 15:07:44 +0000316def merge(*iterables):
317 '''Merge multiple sorted inputs into a single sorted output.
318
Guido van Rossumd8faa362007-04-27 19:54:29 +0000319 Similar to sorted(itertools.chain(*iterables)) but returns a generator,
Thomas Wouterscf297e42007-02-23 15:07:44 +0000320 does not pull the data into memory all at once, and assumes that each of
321 the input streams is already sorted (smallest to largest).
322
323 >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
324 [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
325
326 '''
327 _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration
Raymond Hettingerf2762322013-09-11 01:15:40 -0500328 _len = len
Thomas Wouterscf297e42007-02-23 15:07:44 +0000329
330 h = []
331 h_append = h.append
332 for itnum, it in enumerate(map(iter, iterables)):
333 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000334 next = it.__next__
Thomas Wouterscf297e42007-02-23 15:07:44 +0000335 h_append([next(), itnum, next])
336 except _StopIteration:
337 pass
338 heapify(h)
339
Raymond Hettingerf2762322013-09-11 01:15:40 -0500340 while _len(h) > 1:
Thomas Wouterscf297e42007-02-23 15:07:44 +0000341 try:
Raymond Hettingerf2762322013-09-11 01:15:40 -0500342 while True:
343 v, itnum, next = s = h[0]
Thomas Wouterscf297e42007-02-23 15:07:44 +0000344 yield v
345 s[0] = next() # raises StopIteration when exhausted
346 _heapreplace(h, s) # restore heap condition
347 except _StopIteration:
348 _heappop(h) # remove empty iterator
Raymond Hettingerf2762322013-09-11 01:15:40 -0500349 if h:
350 # fast case when only a single iterator remains
351 v, itnum, next = h[0]
352 yield v
353 yield from next.__self__
Thomas Wouterscf297e42007-02-23 15:07:44 +0000354
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700355
356# Algorithm notes for nlargest() and nsmallest()
357# ==============================================
358#
Raymond Hettinger356902d2014-05-19 22:13:45 +0100359# Make a single pass over the data while keeping the k most extreme values
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700360# in a heap. Memory consumption is limited to keeping k values in a list.
361#
362# Measured performance for random inputs:
363#
364# number of comparisons
365# n inputs k-extreme values (average of 5 trials) % more than min()
Raymond Hettinger356902d2014-05-19 22:13:45 +0100366# ------------- ---------------- --------------------- -----------------
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700367# 1,000 100 3,317 133.2%
368# 10,000 100 14,046 40.5%
369# 100,000 100 105,749 5.7%
370# 1,000,000 100 1,007,751 0.8%
371# 10,000,000 100 10,009,401 0.1%
372#
373# Theoretical number of comparisons for k smallest of n random inputs:
374#
375# Step Comparisons Action
376# ---- -------------------------- ---------------------------
377# 1 1.66 * k heapify the first k-inputs
378# 2 n - k compare remaining elements to top of heap
379# 3 k * (1 + lg2(k)) * ln(n/k) replace the topmost value on the heap
380# 4 k * lg2(k) - (k/2) final sort of the k most extreme values
381# Combining and simplifying for a rough estimate gives:
382# comparisons = n + k * (1 + log(n/k)) * (1 + log(k, 2))
383#
384# Computing the number of comparisons for step 3:
385# -----------------------------------------------
386# * For the i-th new value from the iterable, the probability of being in the
387# k most extreme values is k/i. For example, the probability of the 101st
388# value seen being in the 100 most extreme values is 100/101.
389# * If the value is a new extreme value, the cost of inserting it into the
390# heap is 1 + log(k, 2).
391# * The probabilty times the cost gives:
392# (k/i) * (1 + log(k, 2))
393# * Summing across the remaining n-k elements gives:
394# sum((k/i) * (1 + log(k, 2)) for xrange(k+1, n+1))
395# * This reduces to:
396# (H(n) - H(k)) * k * (1 + log(k, 2))
397# * Where H(n) is the n-th harmonic number estimated by:
398# gamma = 0.5772156649
399# H(n) = log(n, e) + gamma + 1.0 / (2.0 * n)
400# http://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#Rate_of_divergence
401# * Substituting the H(n) formula:
402# comparisons = k * (1 + log(k, 2)) * (log(n/k, e) + (1/n - 1/k) / 2)
403#
404# Worst-case for step 3:
405# ----------------------
406# In the worst case, the input data is reversed sorted so that every new element
407# must be inserted in the heap:
408#
409# comparisons = 1.66 * k + log(k, 2) * (n - k)
410#
411# Alternative Algorithms
412# ----------------------
413# Other algorithms were not used because they:
414# 1) Took much more auxiliary memory,
415# 2) Made multiple passes over the data.
416# 3) Made more comparisons in common cases (small k, large n, semi-random input).
417# See the more detailed comparison of approach at:
418# http://code.activestate.com/recipes/577573-compare-algorithms-for-heapqsmallest
419
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000420def nsmallest(n, iterable, key=None):
421 """Find the n smallest elements in a dataset.
422
423 Equivalent to: sorted(iterable, key=key)[:n]
424 """
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700425
Benjamin Peterson18e95122009-01-18 22:46:33 +0000426 # Short-cut for n==1 is to use min() when len(iterable)>0
427 if n == 1:
428 it = iter(iterable)
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700429 sentinel = object()
Benjamin Peterson18e95122009-01-18 22:46:33 +0000430 if key is None:
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700431 result = min(it, default=sentinel)
432 else:
433 result = min(it, default=sentinel, key=key)
434 return [] if result is sentinel else [result]
Benjamin Peterson18e95122009-01-18 22:46:33 +0000435
Éric Araujo395ba352011-04-15 23:34:31 +0200436 # When n>=size, it's faster to use sorted()
Benjamin Peterson18e95122009-01-18 22:46:33 +0000437 try:
438 size = len(iterable)
439 except (TypeError, AttributeError):
440 pass
441 else:
442 if n >= size:
443 return sorted(iterable, key=key)[:n]
444
445 # When key is none, use simpler decoration
Georg Brandl3a9b0622009-01-03 22:07:57 +0000446 if key is None:
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700447 it = iter(iterable)
448 result = list(islice(zip(it, count()), n))
449 if not result:
450 return result
451 _heapify_max(result)
452 order = n
453 top = result[0][0]
454 _heapreplace = _heapreplace_max
455 for elem in it:
456 if elem < top:
457 _heapreplace(result, (elem, order))
458 top = result[0][0]
459 order += 1
460 result.sort()
461 return [r[0] for r in result]
Benjamin Peterson18e95122009-01-18 22:46:33 +0000462
463 # General case, slowest method
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700464 it = iter(iterable)
465 result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
466 if not result:
467 return result
468 _heapify_max(result)
469 order = n
470 top = result[0][0]
471 _heapreplace = _heapreplace_max
472 for elem in it:
473 k = key(elem)
474 if k < top:
475 _heapreplace(result, (k, order, elem))
476 top = result[0][0]
477 order += 1
478 result.sort()
479 return [r[2] for r in result]
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000480
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000481def nlargest(n, iterable, key=None):
482 """Find the n largest elements in a dataset.
483
484 Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
485 """
Benjamin Peterson18e95122009-01-18 22:46:33 +0000486
487 # Short-cut for n==1 is to use max() when len(iterable)>0
488 if n == 1:
489 it = iter(iterable)
Raymond Hettinger277842e2014-05-11 01:55:46 -0700490 sentinel = object()
Benjamin Peterson18e95122009-01-18 22:46:33 +0000491 if key is None:
Raymond Hettinger277842e2014-05-11 01:55:46 -0700492 result = max(it, default=sentinel)
493 else:
494 result = max(it, default=sentinel, key=key)
495 return [] if result is sentinel else [result]
Benjamin Peterson18e95122009-01-18 22:46:33 +0000496
Éric Araujo395ba352011-04-15 23:34:31 +0200497 # When n>=size, it's faster to use sorted()
Benjamin Peterson18e95122009-01-18 22:46:33 +0000498 try:
499 size = len(iterable)
500 except (TypeError, AttributeError):
501 pass
502 else:
503 if n >= size:
504 return sorted(iterable, key=key, reverse=True)[:n]
505
506 # When key is none, use simpler decoration
Georg Brandl3a9b0622009-01-03 22:07:57 +0000507 if key is None:
Raymond Hettinger277842e2014-05-11 01:55:46 -0700508 it = iter(iterable)
509 result = list(islice(zip(it, count(0, -1)), n))
510 if not result:
511 return result
512 heapify(result)
513 order = -n
514 top = result[0][0]
515 _heapreplace = heapreplace
516 for elem in it:
517 if top < elem:
Raymond Hettinger277842e2014-05-11 01:55:46 -0700518 _heapreplace(result, (elem, order))
519 top = result[0][0]
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700520 order -= 1
Raymond Hettinger277842e2014-05-11 01:55:46 -0700521 result.sort(reverse=True)
522 return [r[0] for r in result]
Benjamin Peterson18e95122009-01-18 22:46:33 +0000523
524 # General case, slowest method
Raymond Hettinger277842e2014-05-11 01:55:46 -0700525 it = iter(iterable)
526 result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
527 if not result:
528 return result
529 heapify(result)
530 order = -n
531 top = result[0][0]
532 _heapreplace = heapreplace
533 for elem in it:
534 k = key(elem)
535 if top < k:
Raymond Hettinger277842e2014-05-11 01:55:46 -0700536 _heapreplace(result, (k, order, elem))
537 top = result[0][0]
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700538 order -= 1
Raymond Hettinger277842e2014-05-11 01:55:46 -0700539 result.sort(reverse=True)
540 return [r[2] for r in result]
541
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000542
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000543if __name__ == "__main__":
Thomas Wouterscf297e42007-02-23 15:07:44 +0000544
545 import doctest
546 doctest.testmod()