blob: 7e33e7481467faa9176f0a2d5f055464affc8166 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`heapq` --- Heap queue algorithm
2=====================================
3
4.. module:: heapq
5 :synopsis: Heap queue algorithm (a.k.a. priority queue).
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Kevin O'Connor
8.. sectionauthor:: Guido van Rossum <guido@python.org>
9.. sectionauthor:: François Pinard
Raymond Hettinger0e833c32010-08-07 23:31:27 +000010.. sectionauthor:: Raymond Hettinger
Georg Brandl116aa622007-08-15 14:28:22 +000011
Raymond Hettinger10480942011-01-10 03:26:08 +000012**Source code:** :source:`Lib/heapq.py`
13
Raymond Hettinger4f707fd2011-01-10 19:54:11 +000014--------------
15
Georg Brandl116aa622007-08-15 14:28:22 +000016This module provides an implementation of the heap queue algorithm, also known
17as the priority queue algorithm.
18
Georg Brandl57410c12010-11-23 08:37:54 +000019Heaps 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]``.
Georg Brandl116aa622007-08-15 14:28:22 +000025
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
Eli Bendersky39430da2015-03-14 20:14:23 -070051 invariant. If the heap is empty, :exc:`IndexError` is raised. To access the
52 smallest item without popping it, use ``heap[0]``.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Benjamin Peterson35e8c462008-04-24 02:34:53 +000054
Christian Heimesdd15f6c2008-03-16 00:07:10 +000055.. 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
Georg Brandl116aa622007-08-15 14:28:22 +000061
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.
Georg Brandl116aa622007-08-15 14:28:22 +000071
Raymond Hettinger6f80b4c2010-09-01 21:27:31 +000072 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*.
Georg Brandl116aa622007-08-15 14:28:22 +000076
Raymond Hettinger6f80b4c2010-09-01 21:27:31 +000077 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.
Georg Brandlaf265f42008-12-07 15:06:20 +000081
Georg Brandl48310cd2009-01-03 21:18:54 +000082
Georg Brandl116aa622007-08-15 14:28:22 +000083The module also offers three general purpose functions based on heaps.
84
85
Raymond Hettinger35db4392014-05-30 02:28:36 -070086.. function:: merge(*iterables, key=None, reverse=False)
Georg Brandl116aa622007-08-15 14:28:22 +000087
88 Merge multiple sorted inputs into a single sorted output (for example, merge
Georg Brandl9afde1c2007-11-01 20:32:30 +000089 timestamped entries from multiple log files). Returns an :term:`iterator`
Benjamin Peterson206e3072008-10-19 14:07:49 +000090 over the sorted values.
Georg Brandl116aa622007-08-15 14:28:22 +000091
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
Raymond Hettinger35db4392014-05-30 02:28:36 -070096 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.
104
105 .. versionchanged:: 3.5
106 Added the optional *key* and *reverse* parameters.
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108
Georg Brandl036490d2009-05-17 13:00:36 +0000109.. function:: nlargest(n, iterable, key=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111 Return a list with the *n* largest elements from the dataset defined by
112 *iterable*. *key*, if provided, specifies a function of one argument that is
113 used to extract a comparison key from each element in the iterable:
114 ``key=str.lower`` Equivalent to: ``sorted(iterable, key=key,
115 reverse=True)[:n]``
116
Georg Brandl116aa622007-08-15 14:28:22 +0000117
Georg Brandl036490d2009-05-17 13:00:36 +0000118.. function:: nsmallest(n, iterable, key=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120 Return a list with the *n* smallest elements from the dataset defined by
121 *iterable*. *key*, if provided, specifies a function of one argument that is
122 used to extract a comparison key from each element in the iterable:
123 ``key=str.lower`` Equivalent to: ``sorted(iterable, key=key)[:n]``
124
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126The latter two functions perform best for smaller values of *n*. For larger
127values, it is more efficient to use the :func:`sorted` function. Also, when
Georg Brandl22b34312009-07-26 14:54:51 +0000128``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max`
Eli Bendersky39430da2015-03-14 20:14:23 -0700129functions. If repeated usage of these functions is required, consider turning
130the iterable into an actual heap.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132
Raymond Hettinger6f80b4c2010-09-01 21:27:31 +0000133Basic Examples
134--------------
135
Georg Brandl5d941342016-02-26 19:37:12 +0100136A `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_ can be implemented by
Raymond Hettinger6f80b4c2010-09-01 21:27:31 +0000137pushing all values onto a heap and then popping off the smallest values one at a
138time::
139
140 >>> def heapsort(iterable):
Raymond Hettinger6f80b4c2010-09-01 21:27:31 +0000141 ... h = []
142 ... for value in iterable:
143 ... heappush(h, value)
144 ... return [heappop(h) for i in range(len(h))]
145 ...
146 >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
147 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
148
Ezio Melotti9b1e92f2014-10-28 12:57:11 +0100149This is similar to ``sorted(iterable)``, but unlike :func:`sorted`, this
150implementation is not stable.
151
Raymond Hettinger6f80b4c2010-09-01 21:27:31 +0000152Heap elements can be tuples. This is useful for assigning comparison values
153(such as task priorities) alongside the main record being tracked::
154
155 >>> h = []
156 >>> heappush(h, (5, 'write code'))
157 >>> heappush(h, (7, 'release product'))
158 >>> heappush(h, (1, 'write spec'))
159 >>> heappush(h, (3, 'create tests'))
160 >>> heappop(h)
161 (1, 'write spec')
162
163
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000164Priority Queue Implementation Notes
165-----------------------------------
166
Georg Brandl5d941342016-02-26 19:37:12 +0100167A `priority queue <https://en.wikipedia.org/wiki/Priority_queue>`_ is common use
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000168for a heap, and it presents several implementation challenges:
169
170* Sort stability: how do you get two tasks with equal priorities to be returned
171 in the order they were originally added?
172
173* Tuple comparison breaks for (priority, task) pairs if the priorities are equal
174 and the tasks do not have a default comparison order.
175
Raymond Hettinger648e7252010-08-07 23:37:37 +0000176* If the priority of a task changes, how do you move it to a new position in
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000177 the heap?
178
179* Or if a pending task needs to be deleted, how do you find it and remove it
180 from the queue?
181
182A solution to the first two challenges is to store entries as 3-element list
183including the priority, an entry count, and the task. The entry count serves as
184a tie-breaker so that two tasks with the same priority are returned in the order
185they were added. And since no two entry counts are the same, the tuple
186comparison will never attempt to directly compare two tasks.
187
188The remaining challenges revolve around finding a pending task and making
189changes to its priority or removing it entirely. Finding a task can be done
190with a dictionary pointing to an entry in the queue.
191
192Removing the entry or changing its priority is more difficult because it would
Raymond Hettingerdf7c4cd2011-10-09 17:28:14 +0100193break the heap structure invariants. So, a possible solution is to mark the
194entry as removed and add a new entry with the revised priority::
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000195
Raymond Hettingerdf7c4cd2011-10-09 17:28:14 +0100196 pq = [] # list of entries arranged in a heap
197 entry_finder = {} # mapping of tasks to entries
198 REMOVED = '<removed-task>' # placeholder for a removed task
199 counter = itertools.count() # unique sequence count
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000200
Raymond Hettingerdf7c4cd2011-10-09 17:28:14 +0100201 def add_task(task, priority=0):
202 'Add a new task or update the priority of an existing task'
203 if task in entry_finder:
204 remove_task(task)
205 count = next(counter)
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000206 entry = [priority, count, task]
Raymond Hettingerdf7c4cd2011-10-09 17:28:14 +0100207 entry_finder[task] = entry
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000208 heappush(pq, entry)
209
Raymond Hettingerdf7c4cd2011-10-09 17:28:14 +0100210 def remove_task(task):
211 'Mark an existing task as REMOVED. Raise KeyError if not found.'
212 entry = entry_finder.pop(task)
213 entry[-1] = REMOVED
214
215 def pop_task():
216 'Remove and return the lowest priority task. Raise KeyError if empty.'
217 while pq:
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000218 priority, count, task = heappop(pq)
Raymond Hettingerdf7c4cd2011-10-09 17:28:14 +0100219 if task is not REMOVED:
220 del entry_finder[task]
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000221 return task
Raymond Hettingerdf7c4cd2011-10-09 17:28:14 +0100222 raise KeyError('pop from an empty priority queue')
Raymond Hettinger0e833c32010-08-07 23:31:27 +0000223
224
Georg Brandl116aa622007-08-15 14:28:22 +0000225Theory
226------
227
Georg Brandl116aa622007-08-15 14:28:22 +0000228Heaps are arrays for which ``a[k] <= a[2*k+1]`` and ``a[k] <= a[2*k+2]`` for all
229*k*, counting elements from 0. For the sake of comparison, non-existing
230elements are considered to be infinite. The interesting property of a heap is
231that ``a[0]`` is always its smallest element.
232
233The strange invariant above is meant to be an efficient memory representation
234for a tournament. The numbers below are *k*, not ``a[k]``::
235
236 0
237
238 1 2
239
240 3 4 5 6
241
242 7 8 9 10 11 12 13 14
243
244 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
245
Martin Panter6245cb32016-04-15 02:14:19 +0000246In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In a usual
Georg Brandl116aa622007-08-15 14:28:22 +0000247binary tournament we see in sports, each cell is the winner over the two cells
248it tops, and we can trace the winner down the tree to see all opponents s/he
249had. However, in many computer applications of such tournaments, we do not need
250to trace the history of a winner. To be more memory efficient, when a winner is
251promoted, we try to replace it by something else at a lower level, and the rule
252becomes that a cell and the two cells it tops contain three different items, but
253the top cell "wins" over the two topped cells.
254
255If this heap invariant is protected at all time, index 0 is clearly the overall
256winner. The simplest algorithmic way to remove it and find the "next" winner is
257to move some loser (let's say cell 30 in the diagram above) into the 0 position,
258and then percolate this new 0 down the tree, exchanging values, until the
259invariant is re-established. This is clearly logarithmic on the total number of
260items in the tree. By iterating over all items, you get an O(n log n) sort.
261
262A nice feature of this sort is that you can efficiently insert new items while
263the sort is going on, provided that the inserted items are not "better" than the
264last 0'th element you extracted. This is especially useful in simulation
265contexts, where the tree holds all incoming events, and the "win" condition
Ned Deily676d7aa2013-07-15 19:08:13 -0700266means the smallest scheduled time. When an event schedules other events for
Georg Brandl116aa622007-08-15 14:28:22 +0000267execution, they are scheduled into the future, so they can easily go into the
268heap. So, a heap is a good structure for implementing schedulers (this is what
269I used for my MIDI sequencer :-).
270
271Various structures for implementing schedulers have been extensively studied,
272and heaps are good for this, as they are reasonably speedy, the speed is almost
273constant, and the worst case is not much different than the average case.
274However, there are other representations which are more efficient overall, yet
275the worst cases might be terrible.
276
277Heaps are also very useful in big disk sorts. You most probably all know that a
Raymond Hettingerd2a296a2014-12-11 23:56:32 -0800278big sort implies producing "runs" (which are pre-sorted sequences, whose size is
Georg Brandl116aa622007-08-15 14:28:22 +0000279usually related to the amount of CPU memory), followed by a merging passes for
280these runs, which merging is often very cleverly organised [#]_. It is very
281important that the initial sort produces the longest runs possible. Tournaments
Raymond Hettingerd2a296a2014-12-11 23:56:32 -0800282are a good way to achieve that. If, using all the memory available to hold a
Georg Brandl116aa622007-08-15 14:28:22 +0000283tournament, you replace and percolate items that happen to fit the current run,
284you'll produce runs which are twice the size of the memory for random input, and
285much better for input fuzzily ordered.
286
287Moreover, if you output the 0'th item on disk and get an input which may not fit
288in the current tournament (because the value "wins" over the last output value),
289it cannot fit in the heap, so the size of the heap decreases. The freed memory
290could be cleverly reused immediately for progressively building a second heap,
291which grows at exactly the same rate the first heap is melting. When the first
292heap completely vanishes, you switch heaps and start a new run. Clever and
293quite effective!
294
295In a word, heaps are useful memory structures to know. I use them in a few
296applications, and I think it is good to keep a 'heap' module around. :-)
297
298.. rubric:: Footnotes
299
300.. [#] The disk balancing algorithms which are current, nowadays, are more annoying
301 than clever, and this is a consequence of the seeking capabilities of the disks.
302 On devices which cannot seek, like big tape drives, the story was quite
303 different, and one had to be very clever to ensure (far in advance) that each
304 tape movement will be the most effective possible (that is, will best
305 participate at "progressing" the merge). Some tapes were even able to read
306 backwards, and this was also used to avoid the rewinding time. Believe me, real
307 good tape sorts were quite spectacular to watch! From all times, sorting has
308 always been a Great Art! :-)
309