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