blob: d7658ae2ee095dc6c096405d2528973bd201660b [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
9
Georg Brandl116aa622007-08-15 14:28:22 +000010This module provides an implementation of the heap queue algorithm, also known
11as the priority queue algorithm.
12
13Heaps are arrays for which ``heap[k] <= heap[2*k+1]`` and ``heap[k] <=
14heap[2*k+2]`` for all *k*, counting elements from zero. For the sake of
15comparison, non-existing elements are considered to be infinite. The
16interesting property of a heap is that ``heap[0]`` is always its smallest
17element.
18
19The API below differs from textbook heap algorithms in two aspects: (a) We use
20zero-based indexing. This makes the relationship between the index for a node
21and the indexes for its children slightly less obvious, but is more suitable
22since Python uses zero-based indexing. (b) Our pop method returns the smallest
23item, not the largest (called a "min heap" in textbooks; a "max heap" is more
24common in texts because of its suitability for in-place sorting).
25
26These two make it possible to view the heap as a regular Python list without
27surprises: ``heap[0]`` is the smallest item, and ``heap.sort()`` maintains the
28heap invariant!
29
30To create a heap, use a list initialized to ``[]``, or you can transform a
31populated list into a heap via function :func:`heapify`.
32
33The following functions are provided:
34
35
36.. function:: heappush(heap, item)
37
38 Push the value *item* onto the *heap*, maintaining the heap invariant.
39
40
41.. function:: heappop(heap)
42
43 Pop and return the smallest item from the *heap*, maintaining the heap
44 invariant. If the heap is empty, :exc:`IndexError` is raised.
45
Benjamin Peterson35e8c462008-04-24 02:34:53 +000046
Christian Heimesdd15f6c2008-03-16 00:07:10 +000047.. function:: heappushpop(heap, item)
48
49 Push *item* on the heap, then pop and return the smallest item from the
50 *heap*. The combined action runs more efficiently than :func:`heappush`
51 followed by a separate call to :func:`heappop`.
52
Georg Brandl116aa622007-08-15 14:28:22 +000053
54.. function:: heapify(x)
55
56 Transform list *x* into a heap, in-place, in linear time.
57
58
59.. function:: heapreplace(heap, item)
60
61 Pop and return the smallest item from the *heap*, and also push the new *item*.
62 The heap size doesn't change. If the heap is empty, :exc:`IndexError` is raised.
63 This is more efficient than :func:`heappop` followed by :func:`heappush`, and
64 can be more appropriate when using a fixed-size heap. Note that the value
65 returned may be larger than *item*! That constrains reasonable uses of this
66 routine unless written as part of a conditional replacement::
67
68 if item > heap[0]:
69 item = heapreplace(heap, item)
70
Christian Heimesfe337bf2008-03-23 21:54:12 +000071Example of use:
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 >>> from heapq import heappush, heappop
74 >>> heap = []
75 >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
76 >>> for item in data:
77 ... heappush(heap, item)
78 ...
79 >>> ordered = []
80 >>> while heap:
81 ... ordered.append(heappop(heap))
82 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +000083 >>> ordered
Georg Brandl116aa622007-08-15 14:28:22 +000084 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
85 >>> data.sort()
Georg Brandl6911e3c2007-09-04 07:15:32 +000086 >>> data == ordered
Georg Brandl116aa622007-08-15 14:28:22 +000087 True
Georg Brandl116aa622007-08-15 14:28:22 +000088
Georg Brandlaf265f42008-12-07 15:06:20 +000089Using a heap to insert items at the correct place in a priority queue:
90
91 >>> heap = []
92 >>> data = [(1, 'J'), (4, 'N'), (3, 'H'), (2, 'O')]
93 >>> for item in data:
94 ... heappush(heap, item)
95 ...
96 >>> while heap:
97 ... print(heappop(heap)[1])
98 J
99 O
100 H
101 N
102
Georg Brandl48310cd2009-01-03 21:18:54 +0000103
Georg Brandl116aa622007-08-15 14:28:22 +0000104The module also offers three general purpose functions based on heaps.
105
106
107.. function:: merge(*iterables)
108
109 Merge multiple sorted inputs into a single sorted output (for example, merge
Georg Brandl9afde1c2007-11-01 20:32:30 +0000110 timestamped entries from multiple log files). Returns an :term:`iterator`
Benjamin Peterson206e3072008-10-19 14:07:49 +0000111 over the sorted values.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113 Similar to ``sorted(itertools.chain(*iterables))`` but returns an iterable, does
114 not pull the data into memory all at once, and assumes that each of the input
115 streams is already sorted (smallest to largest).
116
Georg Brandl116aa622007-08-15 14:28:22 +0000117
Georg Brandl036490d2009-05-17 13:00:36 +0000118.. function:: nlargest(n, iterable, key=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120 Return a list with the *n* largest 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,
124 reverse=True)[:n]``
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Georg Brandl036490d2009-05-17 13:00:36 +0000127.. function:: nsmallest(n, iterable, key=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 Return a list with the *n* smallest elements from the dataset defined by
130 *iterable*. *key*, if provided, specifies a function of one argument that is
131 used to extract a comparison key from each element in the iterable:
132 ``key=str.lower`` Equivalent to: ``sorted(iterable, key=key)[:n]``
133
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135The latter two functions perform best for smaller values of *n*. For larger
136values, it is more efficient to use the :func:`sorted` function. Also, when
Georg Brandl22b34312009-07-26 14:54:51 +0000137``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max`
Georg Brandl116aa622007-08-15 14:28:22 +0000138functions.
139
140
141Theory
142------
143
144(This explanation is due to François Pinard. The Python code for this module
145was contributed by Kevin O'Connor.)
146
147Heaps are arrays for which ``a[k] <= a[2*k+1]`` and ``a[k] <= a[2*k+2]`` for all
148*k*, counting elements from 0. For the sake of comparison, non-existing
149elements are considered to be infinite. The interesting property of a heap is
150that ``a[0]`` is always its smallest element.
151
152The strange invariant above is meant to be an efficient memory representation
153for a tournament. The numbers below are *k*, not ``a[k]``::
154
155 0
156
157 1 2
158
159 3 4 5 6
160
161 7 8 9 10 11 12 13 14
162
163 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
164
165In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In an usual
166binary tournament we see in sports, each cell is the winner over the two cells
167it tops, and we can trace the winner down the tree to see all opponents s/he
168had. However, in many computer applications of such tournaments, we do not need
169to trace the history of a winner. To be more memory efficient, when a winner is
170promoted, we try to replace it by something else at a lower level, and the rule
171becomes that a cell and the two cells it tops contain three different items, but
172the top cell "wins" over the two topped cells.
173
174If this heap invariant is protected at all time, index 0 is clearly the overall
175winner. The simplest algorithmic way to remove it and find the "next" winner is
176to move some loser (let's say cell 30 in the diagram above) into the 0 position,
177and then percolate this new 0 down the tree, exchanging values, until the
178invariant is re-established. This is clearly logarithmic on the total number of
179items in the tree. By iterating over all items, you get an O(n log n) sort.
180
181A nice feature of this sort is that you can efficiently insert new items while
182the sort is going on, provided that the inserted items are not "better" than the
183last 0'th element you extracted. This is especially useful in simulation
184contexts, where the tree holds all incoming events, and the "win" condition
185means the smallest scheduled time. When an event schedule other events for
186execution, they are scheduled into the future, so they can easily go into the
187heap. So, a heap is a good structure for implementing schedulers (this is what
188I used for my MIDI sequencer :-).
189
190Various structures for implementing schedulers have been extensively studied,
191and heaps are good for this, as they are reasonably speedy, the speed is almost
192constant, and the worst case is not much different than the average case.
193However, there are other representations which are more efficient overall, yet
194the worst cases might be terrible.
195
196Heaps are also very useful in big disk sorts. You most probably all know that a
197big sort implies producing "runs" (which are pre-sorted sequences, which size is
198usually related to the amount of CPU memory), followed by a merging passes for
199these runs, which merging is often very cleverly organised [#]_. It is very
200important that the initial sort produces the longest runs possible. Tournaments
201are a good way to that. If, using all the memory available to hold a
202tournament, you replace and percolate items that happen to fit the current run,
203you'll produce runs which are twice the size of the memory for random input, and
204much better for input fuzzily ordered.
205
206Moreover, if you output the 0'th item on disk and get an input which may not fit
207in the current tournament (because the value "wins" over the last output value),
208it cannot fit in the heap, so the size of the heap decreases. The freed memory
209could be cleverly reused immediately for progressively building a second heap,
210which grows at exactly the same rate the first heap is melting. When the first
211heap completely vanishes, you switch heaps and start a new run. Clever and
212quite effective!
213
214In a word, heaps are useful memory structures to know. I use them in a few
215applications, and I think it is good to keep a 'heap' module around. :-)
216
217.. rubric:: Footnotes
218
219.. [#] The disk balancing algorithms which are current, nowadays, are more annoying
220 than clever, and this is a consequence of the seeking capabilities of the disks.
221 On devices which cannot seek, like big tape drives, the story was quite
222 different, and one had to be very clever to ensure (far in advance) that each
223 tape movement will be the most effective possible (that is, will best
224 participate at "progressing" the merge). Some tapes were even able to read
225 backwards, and this was also used to avoid the rewinding time. Believe me, real
226 good tape sorts were quite spectacular to watch! From all times, sorting has
227 always been a Great Art! :-)
228