blob: d1aaaae6008cdc9ac90f92ee9006e11043ec17e7 [file] [log] [blame]
Guido van Rossum97512162002-08-02 18:03:24 +00001\section{\module{heapq} ---
2 Heap queue algorithm}
3
4\declaremodule{standard}{heapq}
5\modulesynopsis{Heap queue algorithm (a.k.a. priority queue).}
Fred Drake1acab692002-08-02 19:46:42 +00006\moduleauthor{Kevin O'Connor}{}
Guido van Rossum97512162002-08-02 18:03:24 +00007\sectionauthor{Guido van Rossum}{guido@python.org}
Fred Drake1acab692002-08-02 19:46:42 +00008% Theoretical explanation:
9\sectionauthor{Fran\c cois Pinard}{}
10\versionadded{2.3}
Guido van Rossum97512162002-08-02 18:03:24 +000011
12
13This module provides an implementation of the heap queue algorithm,
14also known as the priority queue algorithm.
Guido van Rossum97512162002-08-02 18:03:24 +000015
16Heaps are arrays for which
17\code{\var{heap}[\var{k}] <= \var{heap}[2*\var{k}+1]} and
18\code{\var{heap}[\var{k}] <= \var{heap}[2*\var{k}+2]}
19for all \var{k}, counting elements from zero. For the sake of
20comparison, non-existing elements are considered to be infinite. The
21interesting property of a heap is that \code{\var{heap}[0]} is always
22its smallest element.
23
24The API below differs from textbook heap algorithms in two aspects:
25(a) We use zero-based indexing. This makes the relationship between the
26index for a node and the indexes for its children slightly less
27obvious, but is more suitable since Python uses zero-based indexing.
Tim Peters6e0da822002-08-03 18:02:09 +000028(b) Our pop method returns the smallest item, not the largest (called a
29"min heap" in textbooks; a "max heap" is more common in texts because
30of its suitability for in-place sorting).
Guido van Rossum97512162002-08-02 18:03:24 +000031
32These two make it possible to view the heap as a regular Python list
33without surprises: \code{\var{heap}[0]} is the smallest item, and
34\code{\var{heap}.sort()} maintains the heap invariant!
35
Tim Peters6e0da822002-08-03 18:02:09 +000036To create a heap, use a list initialized to \code{[]}, or you can
37transform a populated list into a heap via function \function{heapify()}.
Guido van Rossum97512162002-08-02 18:03:24 +000038
39The following functions are provided:
40
41\begin{funcdesc}{heappush}{heap, item}
42Push the value \var{item} onto the \var{heap}, maintaining the
43heap invariant.
44\end{funcdesc}
45
46\begin{funcdesc}{heappop}{heap}
47Pop and return the smallest item from the \var{heap}, maintaining the
48heap invariant.
49\end{funcdesc}
50
Tim Peters6e0da822002-08-03 18:02:09 +000051\begin{funcdesc}{heapify}{x}
52Transform list \var{x} into a heap, in-place, in linear time.
53\end{funcdesc}
54
Guido van Rossum97512162002-08-02 18:03:24 +000055Example of use:
56
57\begin{verbatim}
58>>> from heapq import heappush, heappop
59>>> heap = []
60>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
61>>> for item in data:
62... heappush(heap, item)
Tim Peters6e0da822002-08-03 18:02:09 +000063...
Guido van Rossum97512162002-08-02 18:03:24 +000064>>> sorted = []
65>>> while heap:
66... sorted.append(heappop(heap))
Tim Peters6e0da822002-08-03 18:02:09 +000067...
Guido van Rossum97512162002-08-02 18:03:24 +000068>>> print sorted
69[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
70>>> data.sort()
71>>> print data == sorted
72True
Tim Peters6e0da822002-08-03 18:02:09 +000073>>>
Guido van Rossum97512162002-08-02 18:03:24 +000074\end{verbatim}
75
76
77\subsection{Theory}
78
79(This explanation is due to François Pinard. The Python
80code for this module was contributed by Kevin O'Connor.)
81
82Heaps are arrays for which \code{a[\var{k}] <= a[2*\var{k}+1]} and
83\code{a[\var{k}] <= a[2*\var{k}+2]}
84for all \var{k}, counting elements from 0. For the sake of comparison,
85non-existing elements are considered to be infinite. The interesting
86property of a heap is that \code{a[0]} is always its smallest element.
87
88The strange invariant above is meant to be an efficient memory
89representation for a tournament. The numbers below are \var{k}, not
90\code{a[\var{k}]}:
91
92\begin{verbatim}
93 0
94
95 1 2
96
97 3 4 5 6
98
99 7 8 9 10 11 12 13 14
100
101 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
102\end{verbatim}
103
104In the tree above, each cell \var{k} is topping \code{2*\var{k}+1} and
105\code{2*\var{k}+2}.
106In an usual binary tournament we see in sports, each cell is the winner
107over the two cells it tops, and we can trace the winner down the tree
108to see all opponents s/he had. However, in many computer applications
109of such tournaments, we do not need to trace the history of a winner.
110To be more memory efficient, when a winner is promoted, we try to
111replace it by something else at a lower level, and the rule becomes
112that a cell and the two cells it tops contain three different items,
113but the top cell "wins" over the two topped cells.
114
115If this heap invariant is protected at all time, index 0 is clearly
116the overall winner. The simplest algorithmic way to remove it and
117find the "next" winner is to move some loser (let's say cell 30 in the
118diagram above) into the 0 position, and then percolate this new 0 down
119the tree, exchanging values, until the invariant is re-established.
120This is clearly logarithmic on the total number of items in the tree.
121By iterating over all items, you get an O(n log n) sort.
122
123A nice feature of this sort is that you can efficiently insert new
124items while the sort is going on, provided that the inserted items are
125not "better" than the last 0'th element you extracted. This is
126especially useful in simulation contexts, where the tree holds all
127incoming events, and the "win" condition means the smallest scheduled
128time. When an event schedule other events for execution, they are
129scheduled into the future, so they can easily go into the heap. So, a
130heap is a good structure for implementing schedulers (this is what I
131used for my MIDI sequencer :-).
132
133Various structures for implementing schedulers have been extensively
134studied, and heaps are good for this, as they are reasonably speedy,
135the speed is almost constant, and the worst case is not much different
136than the average case. However, there are other representations which
137are more efficient overall, yet the worst cases might be terrible.
138
139Heaps are also very useful in big disk sorts. You most probably all
140know that a big sort implies producing "runs" (which are pre-sorted
141sequences, which size is usually related to the amount of CPU memory),
142followed by a merging passes for these runs, which merging is often
143very cleverly organised\footnote{The disk balancing algorithms which
144are current, nowadays, are
145more annoying than clever, and this is a consequence of the seeking
146capabilities of the disks. On devices which cannot seek, like big
147tape drives, the story was quite different, and one had to be very
148clever to ensure (far in advance) that each tape movement will be the
149most effective possible (that is, will best participate at
150"progressing" the merge). Some tapes were even able to read
151backwards, and this was also used to avoid the rewinding time.
152Believe me, real good tape sorts were quite spectacular to watch!
153From all times, sorting has always been a Great Art! :-)}.
154It is very important that the initial
155sort produces the longest runs possible. Tournaments are a good way
156to that. If, using all the memory available to hold a tournament, you
157replace and percolate items that happen to fit the current run, you'll
158produce runs which are twice the size of the memory for random input,
159and much better for input fuzzily ordered.
160
161Moreover, if you output the 0'th item on disk and get an input which
162may not fit in the current tournament (because the value "wins" over
163the last output value), it cannot fit in the heap, so the size of the
164heap decreases. The freed memory could be cleverly reused immediately
165for progressively building a second heap, which grows at exactly the
166same rate the first heap is melting. When the first heap completely
167vanishes, you switch heaps and start a new run. Clever and quite
168effective!
169
170In a word, heaps are useful memory structures to know. I use them in
171a few applications, and I think it is good to keep a `heap' module
172around. :-)