blob: 21df796095b8347f9c15ca389e391b68ba3726d1 [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{
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000222 PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000223 int i, n;
224
Raymond Hettingeraefde432004-06-15 23:53:35 +0000225 if (!PyArg_ParseTuple(args, "iO:nlargest", &n, &iterable))
Raymond Hettingerc9297662004-06-12 22:48:46 +0000226 return NULL;
227
228 it = PyObject_GetIter(iterable);
229 if (it == NULL)
230 return NULL;
231
232 heap = PyList_New(0);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000233 if (heap == NULL)
Raymond Hettingerc9297662004-06-12 22:48:46 +0000234 goto fail;
235
236 for (i=0 ; i<n ; i++ ){
237 elem = PyIter_Next(it);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000238 if (elem == NULL) {
239 if (PyErr_Occurred())
240 goto fail;
241 else
242 goto sortit;
243 }
Raymond Hettingerc9297662004-06-12 22:48:46 +0000244 if (PyList_Append(heap, elem) == -1) {
245 Py_DECREF(elem);
246 goto fail;
247 }
248 Py_DECREF(elem);
249 }
250 if (PyList_GET_SIZE(heap) == 0)
251 goto sortit;
252
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000253 for (i=n/2-1 ; i>=0 ; i--)
254 if(_siftup((PyListObject *)heap, i) == -1)
255 goto fail;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000256
257 sol = PyList_GET_ITEM(heap, 0);
258 while (1) {
259 elem = PyIter_Next(it);
260 if (elem == NULL) {
261 if (PyErr_Occurred())
262 goto fail;
263 else
264 goto sortit;
265 }
266 if (PyObject_RichCompareBool(elem, sol, Py_LE)) {
267 Py_DECREF(elem);
268 continue;
269 }
270 oldelem = PyList_GET_ITEM(heap, 0);
271 PyList_SET_ITEM(heap, 0, elem);
272 Py_DECREF(oldelem);
273 if (_siftup((PyListObject *)heap, 0) == -1)
274 goto fail;
275 sol = PyList_GET_ITEM(heap, 0);
276 }
277sortit:
Raymond Hettingerc9297662004-06-12 22:48:46 +0000278 if (PyList_Sort(heap) == -1)
279 goto fail;
280 if (PyList_Reverse(heap) == -1)
281 goto fail;
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000282 Py_DECREF(it);
Raymond Hettingerc9297662004-06-12 22:48:46 +0000283 return heap;
284
285fail:
286 Py_DECREF(it);
287 Py_XDECREF(heap);
288 return NULL;
289}
290
291PyDoc_STRVAR(nlargest_doc,
292"Find the n largest elements in a dataset.\n\
293\n\
294Equivalent to: sorted(iterable, reverse=True)[:n]\n");
295
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000296static int
297_siftdownmax(PyListObject *heap, int startpos, int pos)
298{
299 PyObject *newitem, *parent;
300 int cmp, parentpos;
301
302 assert(PyList_Check(heap));
303 if (pos >= PyList_GET_SIZE(heap)) {
304 PyErr_SetString(PyExc_IndexError, "index out of range");
305 return -1;
306 }
307
308 newitem = PyList_GET_ITEM(heap, pos);
309 Py_INCREF(newitem);
310 /* Follow the path to the root, moving parents down until finding
311 a place newitem fits. */
312 while (pos > startpos){
313 parentpos = (pos - 1) >> 1;
314 parent = PyList_GET_ITEM(heap, parentpos);
315 cmp = PyObject_RichCompareBool(newitem, parent, Py_LE);
316 if (cmp == -1)
317 return -1;
318 if (cmp == 1)
319 break;
320 Py_INCREF(parent);
321 Py_DECREF(PyList_GET_ITEM(heap, pos));
322 PyList_SET_ITEM(heap, pos, parent);
323 pos = parentpos;
324 }
325 Py_DECREF(PyList_GET_ITEM(heap, pos));
326 PyList_SET_ITEM(heap, pos, newitem);
327 return 0;
328}
329
330static int
331_siftupmax(PyListObject *heap, int pos)
332{
333 int startpos, endpos, childpos, rightpos;
334 int cmp;
335 PyObject *newitem, *tmp;
336
337 assert(PyList_Check(heap));
338 endpos = PyList_GET_SIZE(heap);
339 startpos = pos;
340 if (pos >= endpos) {
341 PyErr_SetString(PyExc_IndexError, "index out of range");
342 return -1;
343 }
344 newitem = PyList_GET_ITEM(heap, pos);
345 Py_INCREF(newitem);
346
347 /* Bubble up the smaller child until hitting a leaf. */
348 childpos = 2*pos + 1; /* leftmost child position */
349 while (childpos < endpos) {
350 /* Set childpos to index of smaller child. */
351 rightpos = childpos + 1;
352 if (rightpos < endpos) {
353 cmp = PyObject_RichCompareBool(
354 PyList_GET_ITEM(heap, childpos),
355 PyList_GET_ITEM(heap, rightpos),
356 Py_LE);
357 if (cmp == -1)
358 return -1;
359 if (cmp == 1)
360 childpos = rightpos;
361 }
362 /* Move the smaller child up. */
363 tmp = PyList_GET_ITEM(heap, childpos);
364 Py_INCREF(tmp);
365 Py_DECREF(PyList_GET_ITEM(heap, pos));
366 PyList_SET_ITEM(heap, pos, tmp);
367 pos = childpos;
368 childpos = 2*pos + 1;
369 }
370
371 /* The leaf at pos is empty now. Put newitem there, and and bubble
372 it up to its final resting place (by sifting its parents down). */
373 Py_DECREF(PyList_GET_ITEM(heap, pos));
374 PyList_SET_ITEM(heap, pos, newitem);
375 return _siftdownmax(heap, startpos, pos);
376}
377
378static PyObject *
379nsmallest(PyObject *self, PyObject *args)
380{
381 PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
382 int i, n;
383
Raymond Hettingeraefde432004-06-15 23:53:35 +0000384 if (!PyArg_ParseTuple(args, "iO:nsmallest", &n, &iterable))
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000385 return NULL;
386
387 it = PyObject_GetIter(iterable);
388 if (it == NULL)
389 return NULL;
390
391 heap = PyList_New(0);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000392 if (heap == NULL)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000393 goto fail;
394
395 for (i=0 ; i<n ; i++ ){
396 elem = PyIter_Next(it);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000397 if (elem == NULL) {
398 if (PyErr_Occurred())
399 goto fail;
400 else
401 goto sortit;
402 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000403 if (PyList_Append(heap, elem) == -1) {
404 Py_DECREF(elem);
405 goto fail;
406 }
407 Py_DECREF(elem);
408 }
409 n = PyList_GET_SIZE(heap);
410 if (n == 0)
411 goto sortit;
412
413 for (i=n/2-1 ; i>=0 ; i--)
414 if(_siftupmax((PyListObject *)heap, i) == -1)
415 goto fail;
416
417 los = PyList_GET_ITEM(heap, 0);
418 while (1) {
419 elem = PyIter_Next(it);
420 if (elem == NULL) {
421 if (PyErr_Occurred())
422 goto fail;
423 else
424 goto sortit;
425 }
426 if (PyObject_RichCompareBool(los, elem, Py_LE)) {
427 Py_DECREF(elem);
428 continue;
429 }
430
431 oldelem = PyList_GET_ITEM(heap, 0);
432 PyList_SET_ITEM(heap, 0, elem);
433 Py_DECREF(oldelem);
434 if (_siftupmax((PyListObject *)heap, 0) == -1)
435 goto fail;
436 los = PyList_GET_ITEM(heap, 0);
437 }
438
439sortit:
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000440 if (PyList_Sort(heap) == -1)
441 goto fail;
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000442 Py_DECREF(it);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000443 return heap;
444
445fail:
446 Py_DECREF(it);
447 Py_XDECREF(heap);
448 return NULL;
449}
450
451PyDoc_STRVAR(nsmallest_doc,
452"Find the n smallest elements in a dataset.\n\
453\n\
454Equivalent to: sorted(iterable)[:n]\n");
455
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000456static PyMethodDef heapq_methods[] = {
457 {"heappush", (PyCFunction)heappush,
458 METH_VARARGS, heappush_doc},
459 {"heappop", (PyCFunction)heappop,
460 METH_O, heappop_doc},
461 {"heapreplace", (PyCFunction)heapreplace,
462 METH_VARARGS, heapreplace_doc},
463 {"heapify", (PyCFunction)heapify,
464 METH_O, heapify_doc},
Raymond Hettingerc9297662004-06-12 22:48:46 +0000465 {"nlargest", (PyCFunction)nlargest,
466 METH_VARARGS, nlargest_doc},
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000467 {"nsmallest", (PyCFunction)nsmallest,
468 METH_VARARGS, nsmallest_doc},
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000469 {NULL, NULL} /* sentinel */
470};
471
472PyDoc_STRVAR(module_doc,
473"Heap queue algorithm (a.k.a. priority queue).\n\
474\n\
475Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
476all k, counting elements from 0. For the sake of comparison,\n\
477non-existing elements are considered to be infinite. The interesting\n\
478property of a heap is that a[0] is always its smallest element.\n\
479\n\
480Usage:\n\
481\n\
482heap = [] # creates an empty heap\n\
483heappush(heap, item) # pushes a new item on the heap\n\
484item = heappop(heap) # pops the smallest item from the heap\n\
485item = heap[0] # smallest item on the heap without popping it\n\
486heapify(x) # transforms list into a heap, in-place, in linear time\n\
487item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
488 # new item; the heap size is unchanged\n\
489\n\
490Our API differs from textbook heap algorithms as follows:\n\
491\n\
492- We use 0-based indexing. This makes the relationship between the\n\
493 index for a node and the indexes for its children slightly less\n\
494 obvious, but is more suitable since Python uses 0-based indexing.\n\
495\n\
496- Our heappop() method returns the smallest item, not the largest.\n\
497\n\
498These two make it possible to view the heap as a regular Python list\n\
499without surprises: heap[0] is the smallest item, and heap.sort()\n\
500maintains the heap invariant!\n");
501
502
503PyDoc_STRVAR(__about__,
504"Heap queues\n\
505\n\
506[explanation by François Pinard]\n\
507\n\
508Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
509all k, counting elements from 0. For the sake of comparison,\n\
510non-existing elements are considered to be infinite. The interesting\n\
511property of a heap is that a[0] is always its smallest element.\n"
512"\n\
513The strange invariant above is meant to be an efficient memory\n\
514representation for a tournament. The numbers below are `k', not a[k]:\n\
515\n\
516 0\n\
517\n\
518 1 2\n\
519\n\
520 3 4 5 6\n\
521\n\
522 7 8 9 10 11 12 13 14\n\
523\n\
524 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
525\n\
526\n\
527In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
528an usual binary tournament we see in sports, each cell is the winner\n\
529over the two cells it tops, and we can trace the winner down the tree\n\
530to see all opponents s/he had. However, in many computer applications\n\
531of such tournaments, we do not need to trace the history of a winner.\n\
532To be more memory efficient, when a winner is promoted, we try to\n\
533replace it by something else at a lower level, and the rule becomes\n\
534that a cell and the two cells it tops contain three different items,\n\
535but the top cell \"wins\" over the two topped cells.\n"
536"\n\
537If this heap invariant is protected at all time, index 0 is clearly\n\
538the overall winner. The simplest algorithmic way to remove it and\n\
539find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
540diagram above) into the 0 position, and then percolate this new 0 down\n\
541the tree, exchanging values, until the invariant is re-established.\n\
542This is clearly logarithmic on the total number of items in the tree.\n\
543By iterating over all items, you get an O(n ln n) sort.\n"
544"\n\
545A nice feature of this sort is that you can efficiently insert new\n\
546items while the sort is going on, provided that the inserted items are\n\
547not \"better\" than the last 0'th element you extracted. This is\n\
548especially useful in simulation contexts, where the tree holds all\n\
549incoming events, and the \"win\" condition means the smallest scheduled\n\
550time. When an event schedule other events for execution, they are\n\
551scheduled into the future, so they can easily go into the heap. So, a\n\
552heap is a good structure for implementing schedulers (this is what I\n\
553used for my MIDI sequencer :-).\n"
554"\n\
555Various structures for implementing schedulers have been extensively\n\
556studied, and heaps are good for this, as they are reasonably speedy,\n\
557the speed is almost constant, and the worst case is not much different\n\
558than the average case. However, there are other representations which\n\
559are more efficient overall, yet the worst cases might be terrible.\n"
560"\n\
561Heaps are also very useful in big disk sorts. You most probably all\n\
562know that a big sort implies producing \"runs\" (which are pre-sorted\n\
563sequences, which size is usually related to the amount of CPU memory),\n\
564followed by a merging passes for these runs, which merging is often\n\
565very cleverly organised[1]. It is very important that the initial\n\
566sort produces the longest runs possible. Tournaments are a good way\n\
567to that. If, using all the memory available to hold a tournament, you\n\
568replace and percolate items that happen to fit the current run, you'll\n\
569produce runs which are twice the size of the memory for random input,\n\
570and much better for input fuzzily ordered.\n"
571"\n\
572Moreover, if you output the 0'th item on disk and get an input which\n\
573may not fit in the current tournament (because the value \"wins\" over\n\
574the last output value), it cannot fit in the heap, so the size of the\n\
575heap decreases. The freed memory could be cleverly reused immediately\n\
576for progressively building a second heap, which grows at exactly the\n\
577same rate the first heap is melting. When the first heap completely\n\
578vanishes, you switch heaps and start a new run. Clever and quite\n\
579effective!\n\
580\n\
581In a word, heaps are useful memory structures to know. I use them in\n\
582a few applications, and I think it is good to keep a `heap' module\n\
583around. :-)\n"
584"\n\
585--------------------\n\
586[1] The disk balancing algorithms which are current, nowadays, are\n\
587more annoying than clever, and this is a consequence of the seeking\n\
588capabilities of the disks. On devices which cannot seek, like big\n\
589tape drives, the story was quite different, and one had to be very\n\
590clever to ensure (far in advance) that each tape movement will be the\n\
591most effective possible (that is, will best participate at\n\
592\"progressing\" the merge). Some tapes were even able to read\n\
593backwards, and this was also used to avoid the rewinding time.\n\
594Believe me, real good tape sorts were quite spectacular to watch!\n\
595From all times, sorting has always been a Great Art! :-)\n");
596
597PyMODINIT_FUNC
598init_heapq(void)
599{
600 PyObject *m;
601
602 m = Py_InitModule3("_heapq", heapq_methods, module_doc);
603 PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
604}
605