heapq.py 22 KB

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