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