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