blob: 8e5ce95627f66113527fcccef9bc9982ce2439a9 [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
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
Georg Brandl9afde1c2007-11-01 20:32:30 +000095 timestamped entries from multiple log files). Returns an :term:`iterator`
Benjamin Peterson206e3072008-10-19 14:07:49 +000096 over the sorted values.
Georg Brandl116aa622007-08-15 14:28:22 +000097
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
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103.. function:: nlargest(n, iterable[, key])
104
105 Return a list with the *n* largest elements from the dataset defined by
106 *iterable*. *key*, if provided, specifies a function of one argument that is
107 used to extract a comparison key from each element in the iterable:
108 ``key=str.lower`` Equivalent to: ``sorted(iterable, key=key,
109 reverse=True)[:n]``
110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112.. function:: nsmallest(n, iterable[, key])
113
114 Return a list with the *n* smallest elements from the dataset defined by
115 *iterable*. *key*, if provided, specifies a function of one argument that is
116 used to extract a comparison key from each element in the iterable:
117 ``key=str.lower`` Equivalent to: ``sorted(iterable, key=key)[:n]``
118
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120The latter two functions perform best for smaller values of *n*. For larger
121values, it is more efficient to use the :func:`sorted` function. Also, when
122``n==1``, it is more efficient to use the builtin :func:`min` and :func:`max`
123functions.
124
125
126Theory
127------
128
129(This explanation is due to François Pinard. The Python code for this module
130was contributed by Kevin O'Connor.)
131
132Heaps are arrays for which ``a[k] <= a[2*k+1]`` and ``a[k] <= a[2*k+2]`` for all
133*k*, counting elements from 0. For the sake of comparison, non-existing
134elements are considered to be infinite. The interesting property of a heap is
135that ``a[0]`` is always its smallest element.
136
137The strange invariant above is meant to be an efficient memory representation
138for a tournament. The numbers below are *k*, not ``a[k]``::
139
140 0
141
142 1 2
143
144 3 4 5 6
145
146 7 8 9 10 11 12 13 14
147
148 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
149
150In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In an usual
151binary tournament we see in sports, each cell is the winner over the two cells
152it tops, and we can trace the winner down the tree to see all opponents s/he
153had. However, in many computer applications of such tournaments, we do not need
154to trace the history of a winner. To be more memory efficient, when a winner is
155promoted, we try to replace it by something else at a lower level, and the rule
156becomes that a cell and the two cells it tops contain three different items, but
157the top cell "wins" over the two topped cells.
158
159If this heap invariant is protected at all time, index 0 is clearly the overall
160winner. The simplest algorithmic way to remove it and find the "next" winner is
161to move some loser (let's say cell 30 in the diagram above) into the 0 position,
162and then percolate this new 0 down the tree, exchanging values, until the
163invariant is re-established. This is clearly logarithmic on the total number of
164items in the tree. By iterating over all items, you get an O(n log n) sort.
165
166A nice feature of this sort is that you can efficiently insert new items while
167the sort is going on, provided that the inserted items are not "better" than the
168last 0'th element you extracted. This is especially useful in simulation
169contexts, where the tree holds all incoming events, and the "win" condition
170means the smallest scheduled time. When an event schedule other events for
171execution, they are scheduled into the future, so they can easily go into the
172heap. So, a heap is a good structure for implementing schedulers (this is what
173I used for my MIDI sequencer :-).
174
175Various structures for implementing schedulers have been extensively studied,
176and heaps are good for this, as they are reasonably speedy, the speed is almost
177constant, and the worst case is not much different than the average case.
178However, there are other representations which are more efficient overall, yet
179the worst cases might be terrible.
180
181Heaps are also very useful in big disk sorts. You most probably all know that a
182big sort implies producing "runs" (which are pre-sorted sequences, which size is
183usually related to the amount of CPU memory), followed by a merging passes for
184these runs, which merging is often very cleverly organised [#]_. It is very
185important that the initial sort produces the longest runs possible. Tournaments
186are a good way to that. If, using all the memory available to hold a
187tournament, you replace and percolate items that happen to fit the current run,
188you'll produce runs which are twice the size of the memory for random input, and
189much better for input fuzzily ordered.
190
191Moreover, if you output the 0'th item on disk and get an input which may not fit
192in the current tournament (because the value "wins" over the last output value),
193it cannot fit in the heap, so the size of the heap decreases. The freed memory
194could be cleverly reused immediately for progressively building a second heap,
195which grows at exactly the same rate the first heap is melting. When the first
196heap completely vanishes, you switch heaps and start a new run. Clever and
197quite effective!
198
199In a word, heaps are useful memory structures to know. I use them in a few
200applications, and I think it is good to keep a 'heap' module around. :-)
201
202.. rubric:: Footnotes
203
204.. [#] The disk balancing algorithms which are current, nowadays, are more annoying
205 than clever, and this is a consequence of the seeking capabilities of the disks.
206 On devices which cannot seek, like big tape drives, the story was quite
207 different, and one had to be very clever to ensure (far in advance) that each
208 tape movement will be the most effective possible (that is, will best
209 participate at "progressing" the merge). Some tapes were even able to read
210 backwards, and this was also used to avoid the rewinding time. Believe me, real
211 good tape sorts were quite spectacular to watch! From all times, sorting has
212 always been a Great Art! :-)
213