blob: 8fe742ff0eb6c1fc2f016361cc441e9122c72507 [file] [log] [blame]
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +00001/* Drop in replacement for heapq.py
2
3C implementation derived directly from heapq.py in Py2.3
4which was written by Kevin O'Connor, augmented by Tim Peters,
5annotated by François Pinard, and converted to C by Raymond Hettinger.
6
7*/
8
9#include "Python.h"
10
11static int
12_siftdown(PyListObject *heap, int startpos, int pos)
13{
14 PyObject *newitem, *parent;
15 int cmp, parentpos;
16
17 assert(PyList_Check(heap));
18 if (pos >= PyList_GET_SIZE(heap)) {
19 PyErr_SetString(PyExc_IndexError, "index out of range");
20 return -1;
21 }
22
23 newitem = PyList_GET_ITEM(heap, pos);
24 Py_INCREF(newitem);
25 /* Follow the path to the root, moving parents down until finding
26 a place newitem fits. */
27 while (pos > startpos){
28 parentpos = (pos - 1) >> 1;
29 parent = PyList_GET_ITEM(heap, parentpos);
30 cmp = PyObject_RichCompareBool(parent, newitem, Py_LE);
31 if (cmp == -1)
32 return -1;
33 if (cmp == 1)
34 break;
35 Py_INCREF(parent);
36 Py_DECREF(PyList_GET_ITEM(heap, pos));
37 PyList_SET_ITEM(heap, pos, parent);
38 pos = parentpos;
39 }
40 Py_DECREF(PyList_GET_ITEM(heap, pos));
41 PyList_SET_ITEM(heap, pos, newitem);
42 return 0;
43}
44
45static int
46_siftup(PyListObject *heap, int pos)
47{
48 int startpos, endpos, childpos, rightpos;
49 int cmp;
50 PyObject *newitem, *tmp;
51
52 assert(PyList_Check(heap));
53 endpos = PyList_GET_SIZE(heap);
54 startpos = pos;
55 if (pos >= endpos) {
56 PyErr_SetString(PyExc_IndexError, "index out of range");
57 return -1;
58 }
59 newitem = PyList_GET_ITEM(heap, pos);
60 Py_INCREF(newitem);
61
62 /* Bubble up the smaller child until hitting a leaf. */
63 childpos = 2*pos + 1; /* leftmost child position */
64 while (childpos < endpos) {
65 /* Set childpos to index of smaller child. */
66 rightpos = childpos + 1;
67 if (rightpos < endpos) {
68 cmp = PyObject_RichCompareBool(
69 PyList_GET_ITEM(heap, rightpos),
70 PyList_GET_ITEM(heap, childpos),
71 Py_LE);
72 if (cmp == -1)
73 return -1;
74 if (cmp == 1)
75 childpos = rightpos;
76 }
77 /* Move the smaller child up. */
78 tmp = PyList_GET_ITEM(heap, childpos);
79 Py_INCREF(tmp);
80 Py_DECREF(PyList_GET_ITEM(heap, pos));
81 PyList_SET_ITEM(heap, pos, tmp);
82 pos = childpos;
83 childpos = 2*pos + 1;
84 }
85
86 /* The leaf at pos is empty now. Put newitem there, and and bubble
87 it up to its final resting place (by sifting its parents down). */
88 Py_DECREF(PyList_GET_ITEM(heap, pos));
89 PyList_SET_ITEM(heap, pos, newitem);
90 return _siftdown(heap, startpos, pos);
91}
92
93static PyObject *
94heappush(PyObject *self, PyObject *args)
95{
96 PyObject *heap, *item;
97
98 if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
99 return NULL;
100
101 if (!PyList_Check(heap)) {
102 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
103 return NULL;
104 }
105
106 if (PyList_Append(heap, item) == -1)
107 return NULL;
108
109 if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
110 return NULL;
111 Py_INCREF(Py_None);
112 return Py_None;
113}
114
115PyDoc_STRVAR(heappush_doc,
116"Push item onto heap, maintaining the heap invariant.");
117
118static PyObject *
119heappop(PyObject *self, PyObject *heap)
120{
121 PyObject *lastelt, *returnitem;
122 int n;
123
124 if (!PyList_Check(heap)) {
125 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
126 return NULL;
127 }
128
129 /* # raises appropriate IndexError if heap is empty */
130 n = PyList_GET_SIZE(heap);
131 if (n == 0) {
132 PyErr_SetString(PyExc_IndexError, "index out of range");
133 return NULL;
134 }
135
136 lastelt = PyList_GET_ITEM(heap, n-1) ;
137 Py_INCREF(lastelt);
138 PyList_SetSlice(heap, n-1, n, NULL);
139 n--;
140
141 if (!n)
142 return lastelt;
143 returnitem = PyList_GET_ITEM(heap, 0);
144 PyList_SET_ITEM(heap, 0, lastelt);
145 if (_siftup((PyListObject *)heap, 0) == -1) {
146 Py_DECREF(returnitem);
147 return NULL;
148 }
149 return returnitem;
150}
151
152PyDoc_STRVAR(heappop_doc,
153"Pop the smallest item off the heap, maintaining the heap invariant.");
154
155static PyObject *
156heapreplace(PyObject *self, PyObject *args)
157{
158 PyObject *heap, *item, *returnitem;
159
160 if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
161 return NULL;
162
163 if (!PyList_Check(heap)) {
164 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
165 return NULL;
166 }
167
168 if (PyList_GET_SIZE(heap) < 1) {
169 PyErr_SetString(PyExc_IndexError, "index out of range");
170 return NULL;
171 }
172
173 returnitem = PyList_GET_ITEM(heap, 0);
174 Py_INCREF(item);
175 PyList_SET_ITEM(heap, 0, item);
176 if (_siftup((PyListObject *)heap, 0) == -1) {
177 Py_DECREF(returnitem);
178 return NULL;
179 }
180 return returnitem;
181}
182
183PyDoc_STRVAR(heapreplace_doc,
184"Pop and return the current smallest value, and add the new item.\n\
185\n\
186This is more efficient than heappop() followed by heappush(), and can be\n\
187more appropriate when using a fixed-size heap. Note that the value\n\
188returned may be larger than item! That constrains reasonable uses of\n\
189this routine.\n");
190
191static PyObject *
192heapify(PyObject *self, PyObject *heap)
193{
194 int i, n;
195
196 if (!PyList_Check(heap)) {
197 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
198 return NULL;
199 }
200
201 n = PyList_GET_SIZE(heap);
202 /* Transform bottom-up. The largest index there's any point to
203 looking at is the largest with a child index in-range, so must
204 have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
205 (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
206 n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
207 and that's again n//2-1.
208 */
209 for (i=n/2-1 ; i>=0 ; i--)
210 if(_siftup((PyListObject *)heap, i) == -1)
211 return NULL;
212 Py_INCREF(Py_None);
213 return Py_None;
214}
215
216PyDoc_STRVAR(heapify_doc,
217"Transform list into a heap, in-place, in O(len(heap)) time.");
218
Raymond Hettingerc9297662004-06-12 22:48:46 +0000219static PyObject *
220nlargest(PyObject *self, PyObject *args)
221{
222 PyObject *heap=NULL, *elem, *rv, *iterable, *sol, *it, *oldelem;
223 int i, n;
224
225 if (!PyArg_ParseTuple(args, "Oi:nlargest", &iterable, &n))
226 return NULL;
227
228 it = PyObject_GetIter(iterable);
229 if (it == NULL)
230 return NULL;
231
232 heap = PyList_New(0);
233 if (it == NULL)
234 goto fail;
235
236 for (i=0 ; i<n ; i++ ){
237 elem = PyIter_Next(it);
238 if (elem == NULL)
239 goto sortit;
240 if (PyList_Append(heap, elem) == -1) {
241 Py_DECREF(elem);
242 goto fail;
243 }
244 Py_DECREF(elem);
245 }
246 if (PyList_GET_SIZE(heap) == 0)
247 goto sortit;
248
249 rv = heapify(self, heap);
250 if (rv == NULL)
251 goto fail;
252 Py_DECREF(rv);
253
254 sol = PyList_GET_ITEM(heap, 0);
255 while (1) {
256 elem = PyIter_Next(it);
257 if (elem == NULL) {
258 if (PyErr_Occurred())
259 goto fail;
260 else
261 goto sortit;
262 }
263 if (PyObject_RichCompareBool(elem, sol, Py_LE)) {
264 Py_DECREF(elem);
265 continue;
266 }
267 oldelem = PyList_GET_ITEM(heap, 0);
268 PyList_SET_ITEM(heap, 0, elem);
269 Py_DECREF(oldelem);
270 if (_siftup((PyListObject *)heap, 0) == -1)
271 goto fail;
272 sol = PyList_GET_ITEM(heap, 0);
273 }
274sortit:
275 Py_DECREF(it);
276 if (PyList_Sort(heap) == -1)
277 goto fail;
278 if (PyList_Reverse(heap) == -1)
279 goto fail;
280 return heap;
281
282fail:
283 Py_DECREF(it);
284 Py_XDECREF(heap);
285 return NULL;
286}
287
288PyDoc_STRVAR(nlargest_doc,
289"Find the n largest elements in a dataset.\n\
290\n\
291Equivalent to: sorted(iterable, reverse=True)[:n]\n");
292
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000293static PyMethodDef heapq_methods[] = {
294 {"heappush", (PyCFunction)heappush,
295 METH_VARARGS, heappush_doc},
296 {"heappop", (PyCFunction)heappop,
297 METH_O, heappop_doc},
298 {"heapreplace", (PyCFunction)heapreplace,
299 METH_VARARGS, heapreplace_doc},
300 {"heapify", (PyCFunction)heapify,
301 METH_O, heapify_doc},
Raymond Hettingerc9297662004-06-12 22:48:46 +0000302 {"nlargest", (PyCFunction)nlargest,
303 METH_VARARGS, nlargest_doc},
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000304 {NULL, NULL} /* sentinel */
305};
306
307PyDoc_STRVAR(module_doc,
308"Heap queue algorithm (a.k.a. priority queue).\n\
309\n\
310Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
311all k, counting elements from 0. For the sake of comparison,\n\
312non-existing elements are considered to be infinite. The interesting\n\
313property of a heap is that a[0] is always its smallest element.\n\
314\n\
315Usage:\n\
316\n\
317heap = [] # creates an empty heap\n\
318heappush(heap, item) # pushes a new item on the heap\n\
319item = heappop(heap) # pops the smallest item from the heap\n\
320item = heap[0] # smallest item on the heap without popping it\n\
321heapify(x) # transforms list into a heap, in-place, in linear time\n\
322item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
323 # new item; the heap size is unchanged\n\
324\n\
325Our API differs from textbook heap algorithms as follows:\n\
326\n\
327- We use 0-based indexing. This makes the relationship between the\n\
328 index for a node and the indexes for its children slightly less\n\
329 obvious, but is more suitable since Python uses 0-based indexing.\n\
330\n\
331- Our heappop() method returns the smallest item, not the largest.\n\
332\n\
333These two make it possible to view the heap as a regular Python list\n\
334without surprises: heap[0] is the smallest item, and heap.sort()\n\
335maintains the heap invariant!\n");
336
337
338PyDoc_STRVAR(__about__,
339"Heap queues\n\
340\n\
341[explanation by François Pinard]\n\
342\n\
343Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
344all k, counting elements from 0. For the sake of comparison,\n\
345non-existing elements are considered to be infinite. The interesting\n\
346property of a heap is that a[0] is always its smallest element.\n"
347"\n\
348The strange invariant above is meant to be an efficient memory\n\
349representation for a tournament. The numbers below are `k', not a[k]:\n\
350\n\
351 0\n\
352\n\
353 1 2\n\
354\n\
355 3 4 5 6\n\
356\n\
357 7 8 9 10 11 12 13 14\n\
358\n\
359 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
360\n\
361\n\
362In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
363an usual binary tournament we see in sports, each cell is the winner\n\
364over the two cells it tops, and we can trace the winner down the tree\n\
365to see all opponents s/he had. However, in many computer applications\n\
366of such tournaments, we do not need to trace the history of a winner.\n\
367To be more memory efficient, when a winner is promoted, we try to\n\
368replace it by something else at a lower level, and the rule becomes\n\
369that a cell and the two cells it tops contain three different items,\n\
370but the top cell \"wins\" over the two topped cells.\n"
371"\n\
372If this heap invariant is protected at all time, index 0 is clearly\n\
373the overall winner. The simplest algorithmic way to remove it and\n\
374find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
375diagram above) into the 0 position, and then percolate this new 0 down\n\
376the tree, exchanging values, until the invariant is re-established.\n\
377This is clearly logarithmic on the total number of items in the tree.\n\
378By iterating over all items, you get an O(n ln n) sort.\n"
379"\n\
380A nice feature of this sort is that you can efficiently insert new\n\
381items while the sort is going on, provided that the inserted items are\n\
382not \"better\" than the last 0'th element you extracted. This is\n\
383especially useful in simulation contexts, where the tree holds all\n\
384incoming events, and the \"win\" condition means the smallest scheduled\n\
385time. When an event schedule other events for execution, they are\n\
386scheduled into the future, so they can easily go into the heap. So, a\n\
387heap is a good structure for implementing schedulers (this is what I\n\
388used for my MIDI sequencer :-).\n"
389"\n\
390Various structures for implementing schedulers have been extensively\n\
391studied, and heaps are good for this, as they are reasonably speedy,\n\
392the speed is almost constant, and the worst case is not much different\n\
393than the average case. However, there are other representations which\n\
394are more efficient overall, yet the worst cases might be terrible.\n"
395"\n\
396Heaps are also very useful in big disk sorts. You most probably all\n\
397know that a big sort implies producing \"runs\" (which are pre-sorted\n\
398sequences, which size is usually related to the amount of CPU memory),\n\
399followed by a merging passes for these runs, which merging is often\n\
400very cleverly organised[1]. It is very important that the initial\n\
401sort produces the longest runs possible. Tournaments are a good way\n\
402to that. If, using all the memory available to hold a tournament, you\n\
403replace and percolate items that happen to fit the current run, you'll\n\
404produce runs which are twice the size of the memory for random input,\n\
405and much better for input fuzzily ordered.\n"
406"\n\
407Moreover, if you output the 0'th item on disk and get an input which\n\
408may not fit in the current tournament (because the value \"wins\" over\n\
409the last output value), it cannot fit in the heap, so the size of the\n\
410heap decreases. The freed memory could be cleverly reused immediately\n\
411for progressively building a second heap, which grows at exactly the\n\
412same rate the first heap is melting. When the first heap completely\n\
413vanishes, you switch heaps and start a new run. Clever and quite\n\
414effective!\n\
415\n\
416In a word, heaps are useful memory structures to know. I use them in\n\
417a few applications, and I think it is good to keep a `heap' module\n\
418around. :-)\n"
419"\n\
420--------------------\n\
421[1] The disk balancing algorithms which are current, nowadays, are\n\
422more annoying than clever, and this is a consequence of the seeking\n\
423capabilities of the disks. On devices which cannot seek, like big\n\
424tape drives, the story was quite different, and one had to be very\n\
425clever to ensure (far in advance) that each tape movement will be the\n\
426most effective possible (that is, will best participate at\n\
427\"progressing\" the merge). Some tapes were even able to read\n\
428backwards, and this was also used to avoid the rewinding time.\n\
429Believe me, real good tape sorts were quite spectacular to watch!\n\
430From all times, sorting has always been a Great Art! :-)\n");
431
432PyMODINIT_FUNC
433init_heapq(void)
434{
435 PyObject *m;
436
437 m = Py_InitModule3("_heapq", heapq_methods, module_doc);
438 PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
439}
440