blob: 8edf626effd69aa24564afd40c5b03ce8e9d147b [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
Raymond Hettingerec2fe782008-06-06 21:47:51 +000011/* Older implementations of heapq used Py_LE for comparisons. Now, it uses
12 Py_LT so it will match min(), sorted(), and bisect(). Unfortunately, some
13 client code (Twisted for example) relied on Py_LE, so this little function
14 restores compatability by trying both.
15*/
16static int
17cmp_lt(PyObject *x, PyObject *y)
18{
19 int cmp;
Raymond Hettingerf0bc3cb2008-06-11 12:06:49 +000020
21 if (PyObject_HasAttrString(x, "__lt__"))
22 return PyObject_RichCompareBool(x, y, Py_LT);
23 cmp = PyObject_RichCompareBool(y, x, Py_LE);
24 if (cmp != -1)
25 cmp = 1 - cmp;
Raymond Hettingerec2fe782008-06-06 21:47:51 +000026 return cmp;
27}
28
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000029static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +000030_siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000031{
32 PyObject *newitem, *parent;
Martin v. Löwisad0a4622006-02-16 14:30:23 +000033 int cmp;
34 Py_ssize_t parentpos;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000035
36 assert(PyList_Check(heap));
37 if (pos >= PyList_GET_SIZE(heap)) {
38 PyErr_SetString(PyExc_IndexError, "index out of range");
39 return -1;
40 }
41
42 newitem = PyList_GET_ITEM(heap, pos);
43 Py_INCREF(newitem);
44 /* Follow the path to the root, moving parents down until finding
45 a place newitem fits. */
46 while (pos > startpos){
47 parentpos = (pos - 1) >> 1;
48 parent = PyList_GET_ITEM(heap, parentpos);
Raymond Hettingerec2fe782008-06-06 21:47:51 +000049 cmp = cmp_lt(newitem, parent);
Raymond Hettinger855d9a92004-09-28 00:03:54 +000050 if (cmp == -1) {
51 Py_DECREF(newitem);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000052 return -1;
Raymond Hettinger855d9a92004-09-28 00:03:54 +000053 }
Raymond Hettinger6d7702e2008-05-31 03:24:31 +000054 if (cmp == 0)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000055 break;
56 Py_INCREF(parent);
57 Py_DECREF(PyList_GET_ITEM(heap, pos));
58 PyList_SET_ITEM(heap, pos, parent);
59 pos = parentpos;
60 }
61 Py_DECREF(PyList_GET_ITEM(heap, pos));
62 PyList_SET_ITEM(heap, pos, newitem);
63 return 0;
64}
65
66static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +000067_siftup(PyListObject *heap, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000068{
Martin v. Löwisad0a4622006-02-16 14:30:23 +000069 Py_ssize_t startpos, endpos, childpos, rightpos;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000070 int cmp;
71 PyObject *newitem, *tmp;
72
73 assert(PyList_Check(heap));
74 endpos = PyList_GET_SIZE(heap);
75 startpos = pos;
76 if (pos >= endpos) {
77 PyErr_SetString(PyExc_IndexError, "index out of range");
78 return -1;
79 }
80 newitem = PyList_GET_ITEM(heap, pos);
81 Py_INCREF(newitem);
82
83 /* Bubble up the smaller child until hitting a leaf. */
84 childpos = 2*pos + 1; /* leftmost child position */
85 while (childpos < endpos) {
86 /* Set childpos to index of smaller child. */
87 rightpos = childpos + 1;
88 if (rightpos < endpos) {
Raymond Hettingerec2fe782008-06-06 21:47:51 +000089 cmp = cmp_lt(
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000090 PyList_GET_ITEM(heap, childpos),
Raymond Hettingerec2fe782008-06-06 21:47:51 +000091 PyList_GET_ITEM(heap, rightpos));
Raymond Hettinger855d9a92004-09-28 00:03:54 +000092 if (cmp == -1) {
93 Py_DECREF(newitem);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000094 return -1;
Raymond Hettinger855d9a92004-09-28 00:03:54 +000095 }
Raymond Hettinger6d7702e2008-05-31 03:24:31 +000096 if (cmp == 0)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000097 childpos = rightpos;
98 }
99 /* Move the smaller child up. */
100 tmp = PyList_GET_ITEM(heap, childpos);
101 Py_INCREF(tmp);
102 Py_DECREF(PyList_GET_ITEM(heap, pos));
103 PyList_SET_ITEM(heap, pos, tmp);
104 pos = childpos;
105 childpos = 2*pos + 1;
106 }
107
108 /* The leaf at pos is empty now. Put newitem there, and and bubble
109 it up to its final resting place (by sifting its parents down). */
110 Py_DECREF(PyList_GET_ITEM(heap, pos));
111 PyList_SET_ITEM(heap, pos, newitem);
112 return _siftdown(heap, startpos, pos);
113}
114
115static PyObject *
116heappush(PyObject *self, PyObject *args)
117{
118 PyObject *heap, *item;
119
120 if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
121 return NULL;
122
123 if (!PyList_Check(heap)) {
124 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
125 return NULL;
126 }
127
128 if (PyList_Append(heap, item) == -1)
129 return NULL;
130
131 if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
132 return NULL;
133 Py_INCREF(Py_None);
134 return Py_None;
135}
136
137PyDoc_STRVAR(heappush_doc,
138"Push item onto heap, maintaining the heap invariant.");
139
140static PyObject *
141heappop(PyObject *self, PyObject *heap)
142{
143 PyObject *lastelt, *returnitem;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000144 Py_ssize_t n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000145
146 if (!PyList_Check(heap)) {
147 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
148 return NULL;
149 }
150
151 /* # raises appropriate IndexError if heap is empty */
152 n = PyList_GET_SIZE(heap);
153 if (n == 0) {
154 PyErr_SetString(PyExc_IndexError, "index out of range");
155 return NULL;
156 }
157
158 lastelt = PyList_GET_ITEM(heap, n-1) ;
159 Py_INCREF(lastelt);
160 PyList_SetSlice(heap, n-1, n, NULL);
161 n--;
162
163 if (!n)
164 return lastelt;
165 returnitem = PyList_GET_ITEM(heap, 0);
166 PyList_SET_ITEM(heap, 0, lastelt);
167 if (_siftup((PyListObject *)heap, 0) == -1) {
168 Py_DECREF(returnitem);
169 return NULL;
170 }
171 return returnitem;
172}
173
174PyDoc_STRVAR(heappop_doc,
175"Pop the smallest item off the heap, maintaining the heap invariant.");
176
177static PyObject *
178heapreplace(PyObject *self, PyObject *args)
179{
180 PyObject *heap, *item, *returnitem;
181
182 if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
183 return NULL;
184
185 if (!PyList_Check(heap)) {
186 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
187 return NULL;
188 }
189
190 if (PyList_GET_SIZE(heap) < 1) {
191 PyErr_SetString(PyExc_IndexError, "index out of range");
192 return NULL;
193 }
194
195 returnitem = PyList_GET_ITEM(heap, 0);
196 Py_INCREF(item);
197 PyList_SET_ITEM(heap, 0, item);
198 if (_siftup((PyListObject *)heap, 0) == -1) {
199 Py_DECREF(returnitem);
200 return NULL;
201 }
202 return returnitem;
203}
204
205PyDoc_STRVAR(heapreplace_doc,
206"Pop and return the current smallest value, and add the new item.\n\
207\n\
208This is more efficient than heappop() followed by heappush(), and can be\n\
209more appropriate when using a fixed-size heap. Note that the value\n\
210returned may be larger than item! That constrains reasonable uses of\n\
Raymond Hettinger8158e842004-09-06 07:04:09 +0000211this routine unless written as part of a conditional replacement:\n\n\
212 if item > heap[0]:\n\
213 item = heapreplace(heap, item)\n");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000214
215static PyObject *
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000216heappushpop(PyObject *self, PyObject *args)
217{
218 PyObject *heap, *item, *returnitem;
219 int cmp;
220
221 if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
222 return NULL;
223
224 if (!PyList_Check(heap)) {
225 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
226 return NULL;
227 }
228
229 if (PyList_GET_SIZE(heap) < 1) {
230 Py_INCREF(item);
231 return item;
232 }
233
Raymond Hettingerec2fe782008-06-06 21:47:51 +0000234 cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item);
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000235 if (cmp == -1)
236 return NULL;
Raymond Hettinger6d7702e2008-05-31 03:24:31 +0000237 if (cmp == 0) {
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000238 Py_INCREF(item);
239 return item;
240 }
241
242 returnitem = PyList_GET_ITEM(heap, 0);
243 Py_INCREF(item);
244 PyList_SET_ITEM(heap, 0, item);
245 if (_siftup((PyListObject *)heap, 0) == -1) {
246 Py_DECREF(returnitem);
247 return NULL;
248 }
249 return returnitem;
250}
251
252PyDoc_STRVAR(heappushpop_doc,
253"Push item on the heap, then pop and return the smallest item\n\
254from the heap. The combined action runs more efficiently than\n\
255heappush() followed by a separate call to heappop().");
256
257static PyObject *
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000258heapify(PyObject *self, PyObject *heap)
259{
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000260 Py_ssize_t i, n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000261
262 if (!PyList_Check(heap)) {
263 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
264 return NULL;
265 }
266
267 n = PyList_GET_SIZE(heap);
268 /* Transform bottom-up. The largest index there's any point to
269 looking at is the largest with a child index in-range, so must
270 have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
271 (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
272 n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
273 and that's again n//2-1.
274 */
275 for (i=n/2-1 ; i>=0 ; i--)
276 if(_siftup((PyListObject *)heap, i) == -1)
277 return NULL;
278 Py_INCREF(Py_None);
279 return Py_None;
280}
281
282PyDoc_STRVAR(heapify_doc,
283"Transform list into a heap, in-place, in O(len(heap)) time.");
284
Raymond Hettingerc9297662004-06-12 22:48:46 +0000285static PyObject *
286nlargest(PyObject *self, PyObject *args)
287{
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000288 PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
Thomas Wouters13870b12006-02-16 19:21:53 +0000289 Py_ssize_t i, n;
Raymond Hettinger6d7702e2008-05-31 03:24:31 +0000290 int cmp;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000291
Thomas Wouters13870b12006-02-16 19:21:53 +0000292 if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
Raymond Hettingerc9297662004-06-12 22:48:46 +0000293 return NULL;
294
295 it = PyObject_GetIter(iterable);
296 if (it == NULL)
297 return NULL;
298
299 heap = PyList_New(0);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000300 if (heap == NULL)
Raymond Hettingerc9297662004-06-12 22:48:46 +0000301 goto fail;
302
303 for (i=0 ; i<n ; i++ ){
304 elem = PyIter_Next(it);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000305 if (elem == NULL) {
306 if (PyErr_Occurred())
307 goto fail;
308 else
309 goto sortit;
310 }
Raymond Hettingerc9297662004-06-12 22:48:46 +0000311 if (PyList_Append(heap, elem) == -1) {
312 Py_DECREF(elem);
313 goto fail;
314 }
315 Py_DECREF(elem);
316 }
317 if (PyList_GET_SIZE(heap) == 0)
318 goto sortit;
319
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000320 for (i=n/2-1 ; i>=0 ; i--)
321 if(_siftup((PyListObject *)heap, i) == -1)
322 goto fail;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000323
324 sol = PyList_GET_ITEM(heap, 0);
325 while (1) {
326 elem = PyIter_Next(it);
327 if (elem == NULL) {
328 if (PyErr_Occurred())
329 goto fail;
330 else
331 goto sortit;
332 }
Raymond Hettingerec2fe782008-06-06 21:47:51 +0000333 cmp = cmp_lt(sol, elem);
Raymond Hettinger6d7702e2008-05-31 03:24:31 +0000334 if (cmp == -1) {
335 Py_DECREF(elem);
336 goto fail;
337 }
338 if (cmp == 0) {
Raymond Hettingerc9297662004-06-12 22:48:46 +0000339 Py_DECREF(elem);
340 continue;
341 }
342 oldelem = PyList_GET_ITEM(heap, 0);
343 PyList_SET_ITEM(heap, 0, elem);
344 Py_DECREF(oldelem);
345 if (_siftup((PyListObject *)heap, 0) == -1)
346 goto fail;
347 sol = PyList_GET_ITEM(heap, 0);
348 }
349sortit:
Raymond Hettingerc9297662004-06-12 22:48:46 +0000350 if (PyList_Sort(heap) == -1)
351 goto fail;
352 if (PyList_Reverse(heap) == -1)
353 goto fail;
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000354 Py_DECREF(it);
Raymond Hettingerc9297662004-06-12 22:48:46 +0000355 return heap;
356
357fail:
358 Py_DECREF(it);
359 Py_XDECREF(heap);
360 return NULL;
361}
362
363PyDoc_STRVAR(nlargest_doc,
364"Find the n largest elements in a dataset.\n\
365\n\
366Equivalent to: sorted(iterable, reverse=True)[:n]\n");
367
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000368static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000369_siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000370{
371 PyObject *newitem, *parent;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000372 int cmp;
373 Py_ssize_t parentpos;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000374
375 assert(PyList_Check(heap));
376 if (pos >= PyList_GET_SIZE(heap)) {
377 PyErr_SetString(PyExc_IndexError, "index out of range");
378 return -1;
379 }
380
381 newitem = PyList_GET_ITEM(heap, pos);
382 Py_INCREF(newitem);
383 /* Follow the path to the root, moving parents down until finding
384 a place newitem fits. */
385 while (pos > startpos){
386 parentpos = (pos - 1) >> 1;
387 parent = PyList_GET_ITEM(heap, parentpos);
Raymond Hettingerec2fe782008-06-06 21:47:51 +0000388 cmp = cmp_lt(parent, newitem);
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000389 if (cmp == -1) {
390 Py_DECREF(newitem);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000391 return -1;
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000392 }
Raymond Hettinger6d7702e2008-05-31 03:24:31 +0000393 if (cmp == 0)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000394 break;
395 Py_INCREF(parent);
396 Py_DECREF(PyList_GET_ITEM(heap, pos));
397 PyList_SET_ITEM(heap, pos, parent);
398 pos = parentpos;
399 }
400 Py_DECREF(PyList_GET_ITEM(heap, pos));
401 PyList_SET_ITEM(heap, pos, newitem);
402 return 0;
403}
404
405static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000406_siftupmax(PyListObject *heap, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000407{
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000408 Py_ssize_t startpos, endpos, childpos, rightpos;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000409 int cmp;
410 PyObject *newitem, *tmp;
411
412 assert(PyList_Check(heap));
413 endpos = PyList_GET_SIZE(heap);
414 startpos = pos;
415 if (pos >= endpos) {
416 PyErr_SetString(PyExc_IndexError, "index out of range");
417 return -1;
418 }
419 newitem = PyList_GET_ITEM(heap, pos);
420 Py_INCREF(newitem);
421
422 /* Bubble up the smaller child until hitting a leaf. */
423 childpos = 2*pos + 1; /* leftmost child position */
424 while (childpos < endpos) {
425 /* Set childpos to index of smaller child. */
426 rightpos = childpos + 1;
427 if (rightpos < endpos) {
Raymond Hettingerec2fe782008-06-06 21:47:51 +0000428 cmp = cmp_lt(
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000429 PyList_GET_ITEM(heap, rightpos),
Raymond Hettingerec2fe782008-06-06 21:47:51 +0000430 PyList_GET_ITEM(heap, childpos));
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000431 if (cmp == -1) {
432 Py_DECREF(newitem);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000433 return -1;
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000434 }
Raymond Hettinger6d7702e2008-05-31 03:24:31 +0000435 if (cmp == 0)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000436 childpos = rightpos;
437 }
438 /* Move the smaller child up. */
439 tmp = PyList_GET_ITEM(heap, childpos);
440 Py_INCREF(tmp);
441 Py_DECREF(PyList_GET_ITEM(heap, pos));
442 PyList_SET_ITEM(heap, pos, tmp);
443 pos = childpos;
444 childpos = 2*pos + 1;
445 }
446
447 /* The leaf at pos is empty now. Put newitem there, and and bubble
448 it up to its final resting place (by sifting its parents down). */
449 Py_DECREF(PyList_GET_ITEM(heap, pos));
450 PyList_SET_ITEM(heap, pos, newitem);
451 return _siftdownmax(heap, startpos, pos);
452}
453
454static PyObject *
455nsmallest(PyObject *self, PyObject *args)
456{
457 PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000458 Py_ssize_t i, n;
Raymond Hettinger6d7702e2008-05-31 03:24:31 +0000459 int cmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000460
Thomas Woutersed6254a2006-02-16 17:32:54 +0000461 if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000462 return NULL;
463
464 it = PyObject_GetIter(iterable);
465 if (it == NULL)
466 return NULL;
467
468 heap = PyList_New(0);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000469 if (heap == NULL)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000470 goto fail;
471
472 for (i=0 ; i<n ; i++ ){
473 elem = PyIter_Next(it);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000474 if (elem == NULL) {
475 if (PyErr_Occurred())
476 goto fail;
477 else
478 goto sortit;
479 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000480 if (PyList_Append(heap, elem) == -1) {
481 Py_DECREF(elem);
482 goto fail;
483 }
484 Py_DECREF(elem);
485 }
486 n = PyList_GET_SIZE(heap);
487 if (n == 0)
488 goto sortit;
489
490 for (i=n/2-1 ; i>=0 ; i--)
491 if(_siftupmax((PyListObject *)heap, i) == -1)
492 goto fail;
493
494 los = PyList_GET_ITEM(heap, 0);
495 while (1) {
496 elem = PyIter_Next(it);
497 if (elem == NULL) {
498 if (PyErr_Occurred())
499 goto fail;
500 else
501 goto sortit;
502 }
Raymond Hettingerec2fe782008-06-06 21:47:51 +0000503 cmp = cmp_lt(elem, los);
Raymond Hettinger6d7702e2008-05-31 03:24:31 +0000504 if (cmp == -1) {
505 Py_DECREF(elem);
506 goto fail;
507 }
508 if (cmp == 0) {
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000509 Py_DECREF(elem);
510 continue;
511 }
512
513 oldelem = PyList_GET_ITEM(heap, 0);
514 PyList_SET_ITEM(heap, 0, elem);
515 Py_DECREF(oldelem);
516 if (_siftupmax((PyListObject *)heap, 0) == -1)
517 goto fail;
518 los = PyList_GET_ITEM(heap, 0);
519 }
520
521sortit:
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000522 if (PyList_Sort(heap) == -1)
523 goto fail;
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000524 Py_DECREF(it);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000525 return heap;
526
527fail:
528 Py_DECREF(it);
529 Py_XDECREF(heap);
530 return NULL;
531}
532
533PyDoc_STRVAR(nsmallest_doc,
534"Find the n smallest elements in a dataset.\n\
535\n\
536Equivalent to: sorted(iterable)[:n]\n");
537
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000538static PyMethodDef heapq_methods[] = {
539 {"heappush", (PyCFunction)heappush,
540 METH_VARARGS, heappush_doc},
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000541 {"heappushpop", (PyCFunction)heappushpop,
542 METH_VARARGS, heappushpop_doc},
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000543 {"heappop", (PyCFunction)heappop,
544 METH_O, heappop_doc},
545 {"heapreplace", (PyCFunction)heapreplace,
546 METH_VARARGS, heapreplace_doc},
547 {"heapify", (PyCFunction)heapify,
548 METH_O, heapify_doc},
Raymond Hettingerc9297662004-06-12 22:48:46 +0000549 {"nlargest", (PyCFunction)nlargest,
550 METH_VARARGS, nlargest_doc},
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000551 {"nsmallest", (PyCFunction)nsmallest,
552 METH_VARARGS, nsmallest_doc},
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000553 {NULL, NULL} /* sentinel */
554};
555
556PyDoc_STRVAR(module_doc,
557"Heap queue algorithm (a.k.a. priority queue).\n\
558\n\
559Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
560all k, counting elements from 0. For the sake of comparison,\n\
561non-existing elements are considered to be infinite. The interesting\n\
562property of a heap is that a[0] is always its smallest element.\n\
563\n\
564Usage:\n\
565\n\
566heap = [] # creates an empty heap\n\
567heappush(heap, item) # pushes a new item on the heap\n\
568item = heappop(heap) # pops the smallest item from the heap\n\
569item = heap[0] # smallest item on the heap without popping it\n\
570heapify(x) # transforms list into a heap, in-place, in linear time\n\
571item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
572 # new item; the heap size is unchanged\n\
573\n\
574Our API differs from textbook heap algorithms as follows:\n\
575\n\
576- We use 0-based indexing. This makes the relationship between the\n\
577 index for a node and the indexes for its children slightly less\n\
578 obvious, but is more suitable since Python uses 0-based indexing.\n\
579\n\
580- Our heappop() method returns the smallest item, not the largest.\n\
581\n\
582These two make it possible to view the heap as a regular Python list\n\
583without surprises: heap[0] is the smallest item, and heap.sort()\n\
584maintains the heap invariant!\n");
585
586
587PyDoc_STRVAR(__about__,
588"Heap queues\n\
589\n\
590[explanation by François Pinard]\n\
591\n\
592Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
593all k, counting elements from 0. For the sake of comparison,\n\
594non-existing elements are considered to be infinite. The interesting\n\
595property of a heap is that a[0] is always its smallest element.\n"
596"\n\
597The strange invariant above is meant to be an efficient memory\n\
598representation for a tournament. The numbers below are `k', not a[k]:\n\
599\n\
600 0\n\
601\n\
602 1 2\n\
603\n\
604 3 4 5 6\n\
605\n\
606 7 8 9 10 11 12 13 14\n\
607\n\
608 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
609\n\
610\n\
611In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
612an usual binary tournament we see in sports, each cell is the winner\n\
613over the two cells it tops, and we can trace the winner down the tree\n\
614to see all opponents s/he had. However, in many computer applications\n\
615of such tournaments, we do not need to trace the history of a winner.\n\
616To be more memory efficient, when a winner is promoted, we try to\n\
617replace it by something else at a lower level, and the rule becomes\n\
618that a cell and the two cells it tops contain three different items,\n\
619but the top cell \"wins\" over the two topped cells.\n"
620"\n\
621If this heap invariant is protected at all time, index 0 is clearly\n\
622the overall winner. The simplest algorithmic way to remove it and\n\
623find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
624diagram above) into the 0 position, and then percolate this new 0 down\n\
625the tree, exchanging values, until the invariant is re-established.\n\
626This is clearly logarithmic on the total number of items in the tree.\n\
627By iterating over all items, you get an O(n ln n) sort.\n"
628"\n\
629A nice feature of this sort is that you can efficiently insert new\n\
630items while the sort is going on, provided that the inserted items are\n\
631not \"better\" than the last 0'th element you extracted. This is\n\
632especially useful in simulation contexts, where the tree holds all\n\
633incoming events, and the \"win\" condition means the smallest scheduled\n\
634time. When an event schedule other events for execution, they are\n\
635scheduled into the future, so they can easily go into the heap. So, a\n\
636heap is a good structure for implementing schedulers (this is what I\n\
637used for my MIDI sequencer :-).\n"
638"\n\
639Various structures for implementing schedulers have been extensively\n\
640studied, and heaps are good for this, as they are reasonably speedy,\n\
641the speed is almost constant, and the worst case is not much different\n\
642than the average case. However, there are other representations which\n\
643are more efficient overall, yet the worst cases might be terrible.\n"
644"\n\
645Heaps are also very useful in big disk sorts. You most probably all\n\
646know that a big sort implies producing \"runs\" (which are pre-sorted\n\
647sequences, which size is usually related to the amount of CPU memory),\n\
648followed by a merging passes for these runs, which merging is often\n\
649very cleverly organised[1]. It is very important that the initial\n\
650sort produces the longest runs possible. Tournaments are a good way\n\
651to that. If, using all the memory available to hold a tournament, you\n\
652replace and percolate items that happen to fit the current run, you'll\n\
653produce runs which are twice the size of the memory for random input,\n\
654and much better for input fuzzily ordered.\n"
655"\n\
656Moreover, if you output the 0'th item on disk and get an input which\n\
657may not fit in the current tournament (because the value \"wins\" over\n\
658the last output value), it cannot fit in the heap, so the size of the\n\
659heap decreases. The freed memory could be cleverly reused immediately\n\
660for progressively building a second heap, which grows at exactly the\n\
661same rate the first heap is melting. When the first heap completely\n\
662vanishes, you switch heaps and start a new run. Clever and quite\n\
663effective!\n\
664\n\
665In a word, heaps are useful memory structures to know. I use them in\n\
666a few applications, and I think it is good to keep a `heap' module\n\
667around. :-)\n"
668"\n\
669--------------------\n\
670[1] The disk balancing algorithms which are current, nowadays, are\n\
671more annoying than clever, and this is a consequence of the seeking\n\
672capabilities of the disks. On devices which cannot seek, like big\n\
673tape drives, the story was quite different, and one had to be very\n\
674clever to ensure (far in advance) that each tape movement will be the\n\
675most effective possible (that is, will best participate at\n\
676\"progressing\" the merge). Some tapes were even able to read\n\
677backwards, and this was also used to avoid the rewinding time.\n\
678Believe me, real good tape sorts were quite spectacular to watch!\n\
679From all times, sorting has always been a Great Art! :-)\n");
680
681PyMODINIT_FUNC
682init_heapq(void)
683{
684 PyObject *m;
685
686 m = Py_InitModule3("_heapq", heapq_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000687 if (m == NULL)
688 return;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000689 PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000690}
691