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