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