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