blob: e403a3a10deb317ff11b786e623d6fed26fda1ff [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
Guido van Rossumb2865912002-08-07 18:56:08 +000048heap invariant. If the heap is empty, \exception{IndexError} is raised.
Guido van Rossum97512162002-08-02 18:03:24 +000049\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
Tim Peters0ad679f2002-08-03 18:53:28 +000055\begin{funcdesc}{heapreplace}{heap, item}
56Pop and return the smallest item from the \var{heap}, and also push
57the new \var{item}. The heap size doesn't change.
Guido van Rossumb2865912002-08-07 18:56:08 +000058If the heap is empty, \exception{IndexError} is raised.
Tim Peters0ad679f2002-08-03 18:53:28 +000059This is more efficient than \function{heappop()} followed
60by \function{heappush()}, and can be more appropriate when using
61a fixed-size heap. Note that the value returned may be larger
Raymond Hettinger28224f82004-06-20 09:07:53 +000062than \var{item}! That constrains reasonable uses of this routine
Raymond Hettinger8158e842004-09-06 07:04:09 +000063unless written as part of a conditional replacement:
Raymond Hettinger28224f82004-06-20 09:07:53 +000064\begin{verbatim}
Raymond Hettinger8158e842004-09-06 07:04:09 +000065 if item > heap[0]:
66 item = heapreplace(heap, item)
Raymond Hettinger28224f82004-06-20 09:07:53 +000067\end{verbatim}
Tim Peters0ad679f2002-08-03 18:53:28 +000068\end{funcdesc}
69
Guido van Rossum97512162002-08-02 18:03:24 +000070Example of use:
71
72\begin{verbatim}
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)
Tim Peters6e0da822002-08-03 18:02:09 +000078...
Georg Brandlfafdc3b2006-11-08 10:04:29 +000079>>> ordered = []
Guido van Rossum97512162002-08-02 18:03:24 +000080>>> while heap:
Georg Brandlfafdc3b2006-11-08 10:04:29 +000081... ordered.append(heappop(heap))
Tim Peters6e0da822002-08-03 18:02:09 +000082...
Georg Brandlfafdc3b2006-11-08 10:04:29 +000083>>> print ordered
Guido van Rossum97512162002-08-02 18:03:24 +000084[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
85>>> data.sort()
Georg Brandlfafdc3b2006-11-08 10:04:29 +000086>>> print data == ordered
Guido van Rossum97512162002-08-02 18:03:24 +000087True
Tim Peters6e0da822002-08-03 18:02:09 +000088>>>
Guido van Rossum97512162002-08-02 18:03:24 +000089\end{verbatim}
90
Raymond Hettinger00166c52007-02-19 04:08:43 +000091The module also offers three general purpose functions based on heaps.
92
93\begin{funcdesc}{merge}{*iterables}
94Merge multiple sorted inputs into a single sorted output (for example, merge
95timestamped entries from multiple log files). Returns an iterator over
96over the sorted values.
97
98Similar to \code{sorted(itertools.chain(*iterables))} but returns an iterable,
Raymond Hettingercbac8ce2007-02-19 18:15:04 +000099does not pull the data into memory all at once, and assumes that each of the
100input streams is already sorted (smallest to largest).
Raymond Hettinger00166c52007-02-19 04:08:43 +0000101\versionadded{2.6}
102\end{funcdesc}
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000103
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000104\begin{funcdesc}{nlargest}{n, iterable\optional{, key}}
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000105Return a list with the \var{n} largest elements from the dataset defined
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000106by \var{iterable}. \var{key}, if provided, specifies a function of one
107argument that is used to extract a comparison key from each element
108in the iterable: \samp{\var{key}=\function{str.lower}}
109Equivalent to: \samp{sorted(iterable, key=key, reverse=True)[:n]}
110\versionadded{2.4}
111\versionchanged[Added the optional \var{key} argument]{2.5}
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000112\end{funcdesc}
113
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000114\begin{funcdesc}{nsmallest}{n, iterable\optional{, key}}
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000115Return a list with the \var{n} smallest elements from the dataset defined
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000116by \var{iterable}. \var{key}, if provided, specifies a function of one
117argument that is used to extract a comparison key from each element
118in the iterable: \samp{\var{key}=\function{str.lower}}
119Equivalent to: \samp{sorted(iterable, key=key)[:n]}
120\versionadded{2.4}
121\versionchanged[Added the optional \var{key} argument]{2.5}
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000122\end{funcdesc}
123
Raymond Hettinger00166c52007-02-19 04:08:43 +0000124The latter two functions perform best for smaller values of \var{n}. For larger
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000125values, it is more efficient to use the \function{sorted()} function. Also,
126when \code{n==1}, it is more efficient to use the builtin \function{min()}
127and \function{max()} functions.
128
Guido van Rossum97512162002-08-02 18:03:24 +0000129
130\subsection{Theory}
131
132(This explanation is due to François Pinard. The Python
133code for this module was contributed by Kevin O'Connor.)
134
135Heaps are arrays for which \code{a[\var{k}] <= a[2*\var{k}+1]} and
136\code{a[\var{k}] <= a[2*\var{k}+2]}
137for all \var{k}, counting elements from 0. For the sake of comparison,
138non-existing elements are considered to be infinite. The interesting
139property of a heap is that \code{a[0]} is always its smallest element.
140
141The strange invariant above is meant to be an efficient memory
142representation for a tournament. The numbers below are \var{k}, not
143\code{a[\var{k}]}:
144
145\begin{verbatim}
146 0
147
148 1 2
149
150 3 4 5 6
151
152 7 8 9 10 11 12 13 14
153
154 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
155\end{verbatim}
156
157In the tree above, each cell \var{k} is topping \code{2*\var{k}+1} and
158\code{2*\var{k}+2}.
159In an usual binary tournament we see in sports, each cell is the winner
160over the two cells it tops, and we can trace the winner down the tree
161to see all opponents s/he had. However, in many computer applications
162of such tournaments, we do not need to trace the history of a winner.
163To be more memory efficient, when a winner is promoted, we try to
164replace it by something else at a lower level, and the rule becomes
165that a cell and the two cells it tops contain three different items,
166but the top cell "wins" over the two topped cells.
167
168If this heap invariant is protected at all time, index 0 is clearly
169the overall winner. The simplest algorithmic way to remove it and
170find the "next" winner is to move some loser (let's say cell 30 in the
171diagram above) into the 0 position, and then percolate this new 0 down
172the tree, exchanging values, until the invariant is re-established.
173This is clearly logarithmic on the total number of items in the tree.
174By iterating over all items, you get an O(n log n) sort.
175
176A nice feature of this sort is that you can efficiently insert new
177items while the sort is going on, provided that the inserted items are
178not "better" than the last 0'th element you extracted. This is
179especially useful in simulation contexts, where the tree holds all
180incoming events, and the "win" condition means the smallest scheduled
181time. When an event schedule other events for execution, they are
182scheduled into the future, so they can easily go into the heap. So, a
183heap is a good structure for implementing schedulers (this is what I
184used for my MIDI sequencer :-).
185
186Various structures for implementing schedulers have been extensively
187studied, and heaps are good for this, as they are reasonably speedy,
188the speed is almost constant, and the worst case is not much different
189than the average case. However, there are other representations which
190are more efficient overall, yet the worst cases might be terrible.
191
192Heaps are also very useful in big disk sorts. You most probably all
193know that a big sort implies producing "runs" (which are pre-sorted
194sequences, which size is usually related to the amount of CPU memory),
195followed by a merging passes for these runs, which merging is often
196very cleverly organised\footnote{The disk balancing algorithms which
197are current, nowadays, are
198more annoying than clever, and this is a consequence of the seeking
199capabilities of the disks. On devices which cannot seek, like big
200tape drives, the story was quite different, and one had to be very
201clever to ensure (far in advance) that each tape movement will be the
202most effective possible (that is, will best participate at
203"progressing" the merge). Some tapes were even able to read
204backwards, and this was also used to avoid the rewinding time.
205Believe me, real good tape sorts were quite spectacular to watch!
206From all times, sorting has always been a Great Art! :-)}.
207It is very important that the initial
208sort produces the longest runs possible. Tournaments are a good way
209to that. If, using all the memory available to hold a tournament, you
210replace and percolate items that happen to fit the current run, you'll
211produce runs which are twice the size of the memory for random input,
212and much better for input fuzzily ordered.
213
214Moreover, if you output the 0'th item on disk and get an input which
215may not fit in the current tournament (because the value "wins" over
216the last output value), it cannot fit in the heap, so the size of the
217heap decreases. The freed memory could be cleverly reused immediately
218for progressively building a second heap, which grows at exactly the
219same rate the first heap is melting. When the first heap completely
220vanishes, you switch heaps and start a new run. Clever and quite
221effective!
222
223In a word, heaps are useful memory structures to know. I use them in
224a few applications, and I think it is good to keep a `heap' module
225around. :-)