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