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