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