1:mod:`heapq` --- Heap queue algorithm 2===================================== 3 4.. module:: heapq 5 :synopsis: Heap queue algorithm (a.k.a. priority queue). 6 7.. moduleauthor:: Kevin O'Connor 8.. sectionauthor:: Guido van Rossum <guido@python.org> 9.. sectionauthor:: François Pinard 10.. sectionauthor:: Raymond Hettinger 11 12**Source code:** :source:`Lib/heapq.py` 13 14-------------- 15 16This module provides an implementation of the heap queue algorithm, also known 17as the priority queue algorithm. 18 19Heaps are binary trees for which every parent node has a value less than or 20equal to any of its children. This implementation uses arrays for which 21``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting 22elements from zero. For the sake of comparison, non-existing elements are 23considered to be infinite. The interesting property of a heap is that its 24smallest element is always the root, ``heap[0]``. 25 26The API below differs from textbook heap algorithms in two aspects: (a) We use 27zero-based indexing. This makes the relationship between the index for a node 28and the indexes for its children slightly less obvious, but is more suitable 29since Python uses zero-based indexing. (b) Our pop method returns the smallest 30item, not the largest (called a "min heap" in textbooks; a "max heap" is more 31common in texts because of its suitability for in-place sorting). 32 33These two make it possible to view the heap as a regular Python list without 34surprises: ``heap[0]`` is the smallest item, and ``heap.sort()`` maintains the 35heap invariant! 36 37To create a heap, use a list initialized to ``[]``, or you can transform a 38populated list into a heap via function :func:`heapify`. 39 40The following functions are provided: 41 42 43.. function:: heappush(heap, item) 44 45 Push the value *item* onto the *heap*, maintaining the heap invariant. 46 47 48.. function:: heappop(heap) 49 50 Pop and return the smallest item from the *heap*, maintaining the heap 51 invariant. If the heap is empty, :exc:`IndexError` is raised. To access the 52 smallest item without popping it, use ``heap[0]``. 53 54 55.. function:: heappushpop(heap, item) 56 57 Push *item* on the heap, then pop and return the smallest item from the 58 *heap*. The combined action runs more efficiently than :func:`heappush` 59 followed by a separate call to :func:`heappop`. 60 61 62.. function:: heapify(x) 63 64 Transform list *x* into a heap, in-place, in linear time. 65 66 67.. function:: heapreplace(heap, item) 68 69 Pop and return the smallest item from the *heap*, and also push the new *item*. 70 The heap size doesn't change. If the heap is empty, :exc:`IndexError` is raised. 71 72 This one step operation is more efficient than a :func:`heappop` followed by 73 :func:`heappush` and can be more appropriate when using a fixed-size heap. 74 The pop/push combination always returns an element from the heap and replaces 75 it with *item*. 76 77 The value returned may be larger than the *item* added. If that isn't 78 desired, consider using :func:`heappushpop` instead. Its push/pop 79 combination returns the smaller of the two values, leaving the larger value 80 on the heap. 81 82 83The module also offers three general purpose functions based on heaps. 84 85 86.. function:: merge(*iterables, key=None, reverse=False) 87 88 Merge multiple sorted inputs into a single sorted output (for example, merge 89 timestamped entries from multiple log files). Returns an :term:`iterator` 90 over the sorted values. 91 92 Similar to ``sorted(itertools.chain(*iterables))`` but returns an iterable, does 93 not pull the data into memory all at once, and assumes that each of the input 94 streams is already sorted (smallest to largest). 95 96 Has two optional arguments which must be specified as keyword arguments. 97 98 *key* specifies a :term:`key function` of one argument that is used to 99 extract a comparison key from each input element. The default value is 100 ``None`` (compare the elements directly). 101 102 *reverse* is a boolean value. If set to ``True``, then the input elements 103 are merged as if each comparison were reversed. To achieve behavior similar 104 to ``sorted(itertools.chain(*iterables), reverse=True)``, all iterables must 105 be sorted from largest to smallest. 106 107 .. versionchanged:: 3.5 108 Added the optional *key* and *reverse* parameters. 109 110 111.. function:: nlargest(n, iterable, key=None) 112 113 Return a list with the *n* largest elements from the dataset defined by 114 *iterable*. *key*, if provided, specifies a function of one argument that is 115 used to extract a comparison key from each element in *iterable* (for example, 116 ``key=str.lower``). Equivalent to: ``sorted(iterable, key=key, 117 reverse=True)[:n]``. 118 119 120.. function:: nsmallest(n, iterable, key=None) 121 122 Return a list with the *n* smallest elements from the dataset defined by 123 *iterable*. *key*, if provided, specifies a function of one argument that is 124 used to extract a comparison key from each element in *iterable* (for example, 125 ``key=str.lower``). Equivalent to: ``sorted(iterable, key=key)[:n]``. 126 127 128The latter two functions perform best for smaller values of *n*. For larger 129values, it is more efficient to use the :func:`sorted` function. Also, when 130``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max` 131functions. If repeated usage of these functions is required, consider turning 132the iterable into an actual heap. 133 134 135Basic Examples 136-------------- 137 138A `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_ can be implemented by 139pushing all values onto a heap and then popping off the smallest values one at a 140time:: 141 142 >>> def heapsort(iterable): 143 ... h = [] 144 ... for value in iterable: 145 ... heappush(h, value) 146 ... return [heappop(h) for i in range(len(h))] 147 ... 148 >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]) 149 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 150 151This is similar to ``sorted(iterable)``, but unlike :func:`sorted`, this 152implementation is not stable. 153 154Heap elements can be tuples. This is useful for assigning comparison values 155(such as task priorities) alongside the main record being tracked:: 156 157 >>> h = [] 158 >>> heappush(h, (5, 'write code')) 159 >>> heappush(h, (7, 'release product')) 160 >>> heappush(h, (1, 'write spec')) 161 >>> heappush(h, (3, 'create tests')) 162 >>> heappop(h) 163 (1, 'write spec') 164 165 166Priority Queue Implementation Notes 167----------------------------------- 168 169A `priority queue <https://en.wikipedia.org/wiki/Priority_queue>`_ is common use 170for a heap, and it presents several implementation challenges: 171 172* Sort stability: how do you get two tasks with equal priorities to be returned 173 in the order they were originally added? 174 175* Tuple comparison breaks for (priority, task) pairs if the priorities are equal 176 and the tasks do not have a default comparison order. 177 178* If the priority of a task changes, how do you move it to a new position in 179 the heap? 180 181* Or if a pending task needs to be deleted, how do you find it and remove it 182 from the queue? 183 184A solution to the first two challenges is to store entries as 3-element list 185including the priority, an entry count, and the task. The entry count serves as 186a tie-breaker so that two tasks with the same priority are returned in the order 187they were added. And since no two entry counts are the same, the tuple 188comparison will never attempt to directly compare two tasks. 189 190Another solution to the problem of non-comparable tasks is to create a wrapper 191class that ignores the task item and only compares the priority field:: 192 193 from dataclasses import dataclass, field 194 from typing import Any 195 196 @dataclass(order=True) 197 class PrioritizedItem: 198 priority: int 199 item: Any=field(compare=False) 200 201The remaining challenges revolve around finding a pending task and making 202changes to its priority or removing it entirely. Finding a task can be done 203with a dictionary pointing to an entry in the queue. 204 205Removing the entry or changing its priority is more difficult because it would 206break the heap structure invariants. So, a possible solution is to mark the 207entry as removed and add a new entry with the revised priority:: 208 209 pq = [] # list of entries arranged in a heap 210 entry_finder = {} # mapping of tasks to entries 211 REMOVED = '<removed-task>' # placeholder for a removed task 212 counter = itertools.count() # unique sequence count 213 214 def add_task(task, priority=0): 215 'Add a new task or update the priority of an existing task' 216 if task in entry_finder: 217 remove_task(task) 218 count = next(counter) 219 entry = [priority, count, task] 220 entry_finder[task] = entry 221 heappush(pq, entry) 222 223 def remove_task(task): 224 'Mark an existing task as REMOVED. Raise KeyError if not found.' 225 entry = entry_finder.pop(task) 226 entry[-1] = REMOVED 227 228 def pop_task(): 229 'Remove and return the lowest priority task. Raise KeyError if empty.' 230 while pq: 231 priority, count, task = heappop(pq) 232 if task is not REMOVED: 233 del entry_finder[task] 234 return task 235 raise KeyError('pop from an empty priority queue') 236 237 238Theory 239------ 240 241Heaps are arrays for which ``a[k] <= a[2*k+1]`` and ``a[k] <= a[2*k+2]`` for all 242*k*, counting elements from 0. For the sake of comparison, non-existing 243elements are considered to be infinite. The interesting property of a heap is 244that ``a[0]`` is always its smallest element. 245 246The strange invariant above is meant to be an efficient memory representation 247for a tournament. The numbers below are *k*, not ``a[k]``:: 248 249 0 250 251 1 2 252 253 3 4 5 6 254 255 7 8 9 10 11 12 13 14 256 257 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 258 259In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In a usual 260binary tournament we see in sports, each cell is the winner over the two cells 261it tops, and we can trace the winner down the tree to see all opponents s/he 262had. However, in many computer applications of such tournaments, we do not need 263to trace the history of a winner. To be more memory efficient, when a winner is 264promoted, we try to replace it by something else at a lower level, and the rule 265becomes that a cell and the two cells it tops contain three different items, but 266the top cell "wins" over the two topped cells. 267 268If this heap invariant is protected at all time, index 0 is clearly the overall 269winner. The simplest algorithmic way to remove it and find the "next" winner is 270to move some loser (let's say cell 30 in the diagram above) into the 0 position, 271and then percolate this new 0 down the tree, exchanging values, until the 272invariant is re-established. This is clearly logarithmic on the total number of 273items in the tree. By iterating over all items, you get an O(n log n) sort. 274 275A nice feature of this sort is that you can efficiently insert new items while 276the sort is going on, provided that the inserted items are not "better" than the 277last 0'th element you extracted. This is especially useful in simulation 278contexts, where the tree holds all incoming events, and the "win" condition 279means the smallest scheduled time. When an event schedules other events for 280execution, they are scheduled into the future, so they can easily go into the 281heap. So, a heap is a good structure for implementing schedulers (this is what 282I used for my MIDI sequencer :-). 283 284Various structures for implementing schedulers have been extensively studied, 285and heaps are good for this, as they are reasonably speedy, the speed is almost 286constant, and the worst case is not much different than the average case. 287However, there are other representations which are more efficient overall, yet 288the worst cases might be terrible. 289 290Heaps are also very useful in big disk sorts. You most probably all know that a 291big sort implies producing "runs" (which are pre-sorted sequences, whose size is 292usually related to the amount of CPU memory), followed by a merging passes for 293these runs, which merging is often very cleverly organised [#]_. It is very 294important that the initial sort produces the longest runs possible. Tournaments 295are a good way to achieve that. If, using all the memory available to hold a 296tournament, you replace and percolate items that happen to fit the current run, 297you'll produce runs which are twice the size of the memory for random input, and 298much better for input fuzzily ordered. 299 300Moreover, if you output the 0'th item on disk and get an input which may not fit 301in the current tournament (because the value "wins" over the last output value), 302it cannot fit in the heap, so the size of the heap decreases. The freed memory 303could be cleverly reused immediately for progressively building a second heap, 304which grows at exactly the same rate the first heap is melting. When the first 305heap completely vanishes, you switch heaps and start a new run. Clever and 306quite effective! 307 308In a word, heaps are useful memory structures to know. I use them in a few 309applications, and I think it is good to keep a 'heap' module around. :-) 310 311.. rubric:: Footnotes 312 313.. [#] The disk balancing algorithms which are current, nowadays, are more annoying 314 than clever, and this is a consequence of the seeking capabilities of the disks. 315 On devices which cannot seek, like big tape drives, the story was quite 316 different, and one had to be very clever to ensure (far in advance) that each 317 tape movement will be the most effective possible (that is, will best 318 participate at "progressing" the merge). Some tapes were even able to read 319 backwards, and this was also used to avoid the rewinding time. Believe me, real 320 good tape sorts were quite spectacular to watch! From all times, sorting has 321 always been a Great Art! :-) 322 323