blob: fc24471c32bed1b30800ab43440c709a054f0243 [file] [log] [blame]
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001/* Drop in replacement for heapq.py
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +00002
3C implementation derived directly from heapq.py in Py2.3
4which was written by Kevin O'Connor, augmented by Tim Peters,
Éric Araujo68079582010-09-03 22:06:31 +00005annotated by François Pinard, and converted to C by Raymond Hettinger.
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +00006
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
Ezio Melotti24b07bc2011-03-15 18:55:01 +020014 restores compatibility by trying both.
Raymond Hettingerec2fe782008-06-06 21:47:51 +000015*/
16static int
17cmp_lt(PyObject *x, PyObject *y)
18{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000019 int cmp;
20 static PyObject *lt = NULL;
Raymond Hettingerf0bc3cb2008-06-11 12:06:49 +000021
Antoine Pitrouc83ea132010-05-09 14:46:46 +000022 if (lt == NULL) {
23 lt = PyString_FromString("__lt__");
24 if (lt == NULL)
25 return -1;
26 }
27 if (PyObject_HasAttr(x, lt))
28 return PyObject_RichCompareBool(x, y, Py_LT);
29 cmp = PyObject_RichCompareBool(y, x, Py_LE);
30 if (cmp != -1)
31 cmp = 1 - cmp;
32 return cmp;
Raymond Hettingerec2fe782008-06-06 21:47:51 +000033}
34
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000035static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +000036_siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000037{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000038 PyObject *newitem, *parent;
39 int cmp;
40 Py_ssize_t parentpos;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000041
Antoine Pitrouc83ea132010-05-09 14:46:46 +000042 assert(PyList_Check(heap));
43 if (pos >= PyList_GET_SIZE(heap)) {
44 PyErr_SetString(PyExc_IndexError, "index out of range");
45 return -1;
46 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000047
Antoine Pitrouc83ea132010-05-09 14:46:46 +000048 newitem = PyList_GET_ITEM(heap, pos);
49 Py_INCREF(newitem);
50 /* Follow the path to the root, moving parents down until finding
51 a place newitem fits. */
52 while (pos > startpos){
53 parentpos = (pos - 1) >> 1;
54 parent = PyList_GET_ITEM(heap, parentpos);
55 cmp = cmp_lt(newitem, parent);
56 if (cmp == -1) {
57 Py_DECREF(newitem);
58 return -1;
59 }
60 if (cmp == 0)
61 break;
62 Py_INCREF(parent);
63 Py_DECREF(PyList_GET_ITEM(heap, pos));
64 PyList_SET_ITEM(heap, pos, parent);
65 pos = parentpos;
66 }
67 Py_DECREF(PyList_GET_ITEM(heap, pos));
68 PyList_SET_ITEM(heap, pos, newitem);
69 return 0;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000070}
71
72static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +000073_siftup(PyListObject *heap, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000074{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000075 Py_ssize_t startpos, endpos, childpos, rightpos;
76 int cmp;
77 PyObject *newitem, *tmp;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000078
Antoine Pitrouc83ea132010-05-09 14:46:46 +000079 assert(PyList_Check(heap));
80 endpos = PyList_GET_SIZE(heap);
81 startpos = pos;
82 if (pos >= endpos) {
83 PyErr_SetString(PyExc_IndexError, "index out of range");
84 return -1;
85 }
86 newitem = PyList_GET_ITEM(heap, pos);
87 Py_INCREF(newitem);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000088
Antoine Pitrouc83ea132010-05-09 14:46:46 +000089 /* Bubble up the smaller child until hitting a leaf. */
90 childpos = 2*pos + 1; /* leftmost child position */
91 while (childpos < endpos) {
92 /* Set childpos to index of smaller child. */
93 rightpos = childpos + 1;
94 if (rightpos < endpos) {
95 cmp = cmp_lt(
96 PyList_GET_ITEM(heap, childpos),
97 PyList_GET_ITEM(heap, rightpos));
98 if (cmp == -1) {
99 Py_DECREF(newitem);
100 return -1;
101 }
102 if (cmp == 0)
103 childpos = rightpos;
104 }
105 /* Move the smaller child up. */
106 tmp = PyList_GET_ITEM(heap, childpos);
107 Py_INCREF(tmp);
108 Py_DECREF(PyList_GET_ITEM(heap, pos));
109 PyList_SET_ITEM(heap, pos, tmp);
110 pos = childpos;
111 childpos = 2*pos + 1;
112 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000113
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000114 /* The leaf at pos is empty now. Put newitem there, and and bubble
115 it up to its final resting place (by sifting its parents down). */
116 Py_DECREF(PyList_GET_ITEM(heap, pos));
117 PyList_SET_ITEM(heap, pos, newitem);
118 return _siftdown(heap, startpos, pos);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000119}
120
121static PyObject *
122heappush(PyObject *self, PyObject *args)
123{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000124 PyObject *heap, *item;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000125
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000126 if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
127 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000128
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000129 if (!PyList_Check(heap)) {
130 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
131 return NULL;
132 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000133
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000134 if (PyList_Append(heap, item) == -1)
135 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000136
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000137 if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
138 return NULL;
139 Py_INCREF(Py_None);
140 return Py_None;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000141}
142
143PyDoc_STRVAR(heappush_doc,
Raymond Hettingerbca22092013-01-18 17:35:25 -0800144"heappush(heap, item) -> None. Push item onto heap, maintaining the heap invariant.");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000145
146static PyObject *
147heappop(PyObject *self, PyObject *heap)
148{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000149 PyObject *lastelt, *returnitem;
150 Py_ssize_t n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000151
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000152 if (!PyList_Check(heap)) {
153 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
154 return NULL;
155 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000156
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000157 /* # raises appropriate IndexError if heap is empty */
158 n = PyList_GET_SIZE(heap);
159 if (n == 0) {
160 PyErr_SetString(PyExc_IndexError, "index out of range");
161 return NULL;
162 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000163
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000164 lastelt = PyList_GET_ITEM(heap, n-1) ;
165 Py_INCREF(lastelt);
166 PyList_SetSlice(heap, n-1, n, NULL);
167 n--;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000168
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000169 if (!n)
170 return lastelt;
171 returnitem = PyList_GET_ITEM(heap, 0);
172 PyList_SET_ITEM(heap, 0, lastelt);
173 if (_siftup((PyListObject *)heap, 0) == -1) {
174 Py_DECREF(returnitem);
175 return NULL;
176 }
177 return returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000178}
179
180PyDoc_STRVAR(heappop_doc,
181"Pop the smallest item off the heap, maintaining the heap invariant.");
182
183static PyObject *
184heapreplace(PyObject *self, PyObject *args)
185{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000186 PyObject *heap, *item, *returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000187
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000188 if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
189 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000190
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000191 if (!PyList_Check(heap)) {
192 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
193 return NULL;
194 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000195
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000196 if (PyList_GET_SIZE(heap) < 1) {
197 PyErr_SetString(PyExc_IndexError, "index out of range");
198 return NULL;
199 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000200
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000201 returnitem = PyList_GET_ITEM(heap, 0);
202 Py_INCREF(item);
203 PyList_SET_ITEM(heap, 0, item);
204 if (_siftup((PyListObject *)heap, 0) == -1) {
205 Py_DECREF(returnitem);
206 return NULL;
207 }
208 return returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000209}
210
211PyDoc_STRVAR(heapreplace_doc,
Raymond Hettingerbca22092013-01-18 17:35:25 -0800212"heapreplace(heap, item) -> value. Pop and return the current smallest value, and add the new item.\n\
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000213\n\
214This is more efficient than heappop() followed by heappush(), and can be\n\
215more appropriate when using a fixed-size heap. Note that the value\n\
216returned may be larger than item! That constrains reasonable uses of\n\
Raymond Hettinger8158e842004-09-06 07:04:09 +0000217this routine unless written as part of a conditional replacement:\n\n\
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000218 if item > heap[0]:\n\
219 item = heapreplace(heap, item)\n");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000220
221static PyObject *
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000222heappushpop(PyObject *self, PyObject *args)
223{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000224 PyObject *heap, *item, *returnitem;
225 int cmp;
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000226
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
228 return NULL;
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000229
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000230 if (!PyList_Check(heap)) {
231 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
232 return NULL;
233 }
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000234
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000235 if (PyList_GET_SIZE(heap) < 1) {
236 Py_INCREF(item);
237 return item;
238 }
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000239
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item);
241 if (cmp == -1)
242 return NULL;
243 if (cmp == 0) {
244 Py_INCREF(item);
245 return item;
246 }
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 returnitem = PyList_GET_ITEM(heap, 0);
249 Py_INCREF(item);
250 PyList_SET_ITEM(heap, 0, item);
251 if (_siftup((PyListObject *)heap, 0) == -1) {
252 Py_DECREF(returnitem);
253 return NULL;
254 }
255 return returnitem;
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000256}
257
258PyDoc_STRVAR(heappushpop_doc,
Raymond Hettingerbca22092013-01-18 17:35:25 -0800259"heappushpop(heap, item) -> value. Push item on the heap, then pop and return the smallest item\n\
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000260from the heap. The combined action runs more efficiently than\n\
261heappush() followed by a separate call to heappop().");
262
263static PyObject *
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000264heapify(PyObject *self, PyObject *heap)
265{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000266 Py_ssize_t i, n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000267
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268 if (!PyList_Check(heap)) {
269 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
270 return NULL;
271 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000272
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000273 n = PyList_GET_SIZE(heap);
274 /* Transform bottom-up. The largest index there's any point to
275 looking at is the largest with a child index in-range, so must
276 have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
277 (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
278 n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
279 and that's again n//2-1.
280 */
281 for (i=n/2-1 ; i>=0 ; i--)
282 if(_siftup((PyListObject *)heap, i) == -1)
283 return NULL;
284 Py_INCREF(Py_None);
285 return Py_None;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000286}
287
288PyDoc_STRVAR(heapify_doc,
289"Transform list into a heap, in-place, in O(len(heap)) time.");
290
Raymond Hettingerc9297662004-06-12 22:48:46 +0000291static PyObject *
292nlargest(PyObject *self, PyObject *args)
293{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000294 PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
295 Py_ssize_t i, n;
296 int cmp;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000297
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000298 if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
299 return NULL;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000300
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000301 it = PyObject_GetIter(iterable);
302 if (it == NULL)
303 return NULL;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000304
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000305 heap = PyList_New(0);
306 if (heap == NULL)
307 goto fail;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000308
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000309 for (i=0 ; i<n ; i++ ){
310 elem = PyIter_Next(it);
311 if (elem == NULL) {
312 if (PyErr_Occurred())
313 goto fail;
314 else
315 goto sortit;
316 }
317 if (PyList_Append(heap, elem) == -1) {
318 Py_DECREF(elem);
319 goto fail;
320 }
321 Py_DECREF(elem);
322 }
323 if (PyList_GET_SIZE(heap) == 0)
324 goto sortit;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000325
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000326 for (i=n/2-1 ; i>=0 ; i--)
327 if(_siftup((PyListObject *)heap, i) == -1)
328 goto fail;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000329
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 sol = PyList_GET_ITEM(heap, 0);
331 while (1) {
332 elem = PyIter_Next(it);
333 if (elem == NULL) {
334 if (PyErr_Occurred())
335 goto fail;
336 else
337 goto sortit;
338 }
339 cmp = cmp_lt(sol, elem);
340 if (cmp == -1) {
341 Py_DECREF(elem);
342 goto fail;
343 }
344 if (cmp == 0) {
345 Py_DECREF(elem);
346 continue;
347 }
348 oldelem = PyList_GET_ITEM(heap, 0);
349 PyList_SET_ITEM(heap, 0, elem);
350 Py_DECREF(oldelem);
351 if (_siftup((PyListObject *)heap, 0) == -1)
352 goto fail;
353 sol = PyList_GET_ITEM(heap, 0);
354 }
Raymond Hettingerc9297662004-06-12 22:48:46 +0000355sortit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000356 if (PyList_Sort(heap) == -1)
357 goto fail;
358 if (PyList_Reverse(heap) == -1)
359 goto fail;
360 Py_DECREF(it);
361 return heap;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000362
363fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000364 Py_DECREF(it);
365 Py_XDECREF(heap);
366 return NULL;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000367}
368
369PyDoc_STRVAR(nlargest_doc,
370"Find the n largest elements in a dataset.\n\
371\n\
372Equivalent to: sorted(iterable, reverse=True)[:n]\n");
373
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000374static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000375_siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000376{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000377 PyObject *newitem, *parent;
378 int cmp;
379 Py_ssize_t parentpos;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000380
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000381 assert(PyList_Check(heap));
382 if (pos >= PyList_GET_SIZE(heap)) {
383 PyErr_SetString(PyExc_IndexError, "index out of range");
384 return -1;
385 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000386
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000387 newitem = PyList_GET_ITEM(heap, pos);
388 Py_INCREF(newitem);
389 /* Follow the path to the root, moving parents down until finding
390 a place newitem fits. */
391 while (pos > startpos){
392 parentpos = (pos - 1) >> 1;
393 parent = PyList_GET_ITEM(heap, parentpos);
394 cmp = cmp_lt(parent, newitem);
395 if (cmp == -1) {
396 Py_DECREF(newitem);
397 return -1;
398 }
399 if (cmp == 0)
400 break;
401 Py_INCREF(parent);
402 Py_DECREF(PyList_GET_ITEM(heap, pos));
403 PyList_SET_ITEM(heap, pos, parent);
404 pos = parentpos;
405 }
406 Py_DECREF(PyList_GET_ITEM(heap, pos));
407 PyList_SET_ITEM(heap, pos, newitem);
408 return 0;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000409}
410
411static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000412_siftupmax(PyListObject *heap, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000413{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000414 Py_ssize_t startpos, endpos, childpos, rightpos;
415 int cmp;
416 PyObject *newitem, *tmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000417
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418 assert(PyList_Check(heap));
419 endpos = PyList_GET_SIZE(heap);
420 startpos = pos;
421 if (pos >= endpos) {
422 PyErr_SetString(PyExc_IndexError, "index out of range");
423 return -1;
424 }
425 newitem = PyList_GET_ITEM(heap, pos);
426 Py_INCREF(newitem);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000427
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000428 /* Bubble up the smaller child until hitting a leaf. */
429 childpos = 2*pos + 1; /* leftmost child position */
430 while (childpos < endpos) {
431 /* Set childpos to index of smaller child. */
432 rightpos = childpos + 1;
433 if (rightpos < endpos) {
434 cmp = cmp_lt(
435 PyList_GET_ITEM(heap, rightpos),
436 PyList_GET_ITEM(heap, childpos));
437 if (cmp == -1) {
438 Py_DECREF(newitem);
439 return -1;
440 }
441 if (cmp == 0)
442 childpos = rightpos;
443 }
444 /* Move the smaller child up. */
445 tmp = PyList_GET_ITEM(heap, childpos);
446 Py_INCREF(tmp);
447 Py_DECREF(PyList_GET_ITEM(heap, pos));
448 PyList_SET_ITEM(heap, pos, tmp);
449 pos = childpos;
450 childpos = 2*pos + 1;
451 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000452
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000453 /* The leaf at pos is empty now. Put newitem there, and and bubble
454 it up to its final resting place (by sifting its parents down). */
455 Py_DECREF(PyList_GET_ITEM(heap, pos));
456 PyList_SET_ITEM(heap, pos, newitem);
457 return _siftdownmax(heap, startpos, pos);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000458}
459
460static PyObject *
461nsmallest(PyObject *self, PyObject *args)
462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000463 PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
464 Py_ssize_t i, n;
465 int cmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000466
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000467 if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
468 return NULL;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000469
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000470 it = PyObject_GetIter(iterable);
471 if (it == NULL)
472 return NULL;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000473
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000474 heap = PyList_New(0);
475 if (heap == NULL)
476 goto fail;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000477
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000478 for (i=0 ; i<n ; i++ ){
479 elem = PyIter_Next(it);
480 if (elem == NULL) {
481 if (PyErr_Occurred())
482 goto fail;
483 else
484 goto sortit;
485 }
486 if (PyList_Append(heap, elem) == -1) {
487 Py_DECREF(elem);
488 goto fail;
489 }
490 Py_DECREF(elem);
491 }
492 n = PyList_GET_SIZE(heap);
493 if (n == 0)
494 goto sortit;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000495
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000496 for (i=n/2-1 ; i>=0 ; i--)
497 if(_siftupmax((PyListObject *)heap, i) == -1)
498 goto fail;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000499
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000500 los = PyList_GET_ITEM(heap, 0);
501 while (1) {
502 elem = PyIter_Next(it);
503 if (elem == NULL) {
504 if (PyErr_Occurred())
505 goto fail;
506 else
507 goto sortit;
508 }
509 cmp = cmp_lt(elem, los);
510 if (cmp == -1) {
511 Py_DECREF(elem);
512 goto fail;
513 }
514 if (cmp == 0) {
515 Py_DECREF(elem);
516 continue;
517 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000518
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 oldelem = PyList_GET_ITEM(heap, 0);
520 PyList_SET_ITEM(heap, 0, elem);
521 Py_DECREF(oldelem);
522 if (_siftupmax((PyListObject *)heap, 0) == -1)
523 goto fail;
524 los = PyList_GET_ITEM(heap, 0);
525 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000526
527sortit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 if (PyList_Sort(heap) == -1)
529 goto fail;
530 Py_DECREF(it);
531 return heap;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000532
533fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000534 Py_DECREF(it);
535 Py_XDECREF(heap);
536 return NULL;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000537}
538
539PyDoc_STRVAR(nsmallest_doc,
540"Find the n smallest elements in a dataset.\n\
541\n\
542Equivalent to: sorted(iterable)[:n]\n");
543
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000544static PyMethodDef heapq_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000545 {"heappush", (PyCFunction)heappush,
546 METH_VARARGS, heappush_doc},
547 {"heappushpop", (PyCFunction)heappushpop,
548 METH_VARARGS, heappushpop_doc},
549 {"heappop", (PyCFunction)heappop,
550 METH_O, heappop_doc},
551 {"heapreplace", (PyCFunction)heapreplace,
552 METH_VARARGS, heapreplace_doc},
553 {"heapify", (PyCFunction)heapify,
554 METH_O, heapify_doc},
555 {"nlargest", (PyCFunction)nlargest,
556 METH_VARARGS, nlargest_doc},
557 {"nsmallest", (PyCFunction)nsmallest,
558 METH_VARARGS, nsmallest_doc},
559 {NULL, NULL} /* sentinel */
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000560};
561
562PyDoc_STRVAR(module_doc,
563"Heap queue algorithm (a.k.a. priority queue).\n\
564\n\
565Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
566all k, counting elements from 0. For the sake of comparison,\n\
567non-existing elements are considered to be infinite. The interesting\n\
568property of a heap is that a[0] is always its smallest element.\n\
569\n\
570Usage:\n\
571\n\
572heap = [] # creates an empty heap\n\
573heappush(heap, item) # pushes a new item on the heap\n\
574item = heappop(heap) # pops the smallest item from the heap\n\
575item = heap[0] # smallest item on the heap without popping it\n\
576heapify(x) # transforms list into a heap, in-place, in linear time\n\
577item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
578 # new item; the heap size is unchanged\n\
579\n\
580Our API differs from textbook heap algorithms as follows:\n\
581\n\
582- We use 0-based indexing. This makes the relationship between the\n\
583 index for a node and the indexes for its children slightly less\n\
584 obvious, but is more suitable since Python uses 0-based indexing.\n\
585\n\
586- Our heappop() method returns the smallest item, not the largest.\n\
587\n\
588These two make it possible to view the heap as a regular Python list\n\
589without surprises: heap[0] is the smallest item, and heap.sort()\n\
590maintains the heap invariant!\n");
591
592
593PyDoc_STRVAR(__about__,
594"Heap queues\n\
595\n\
596[explanation by François Pinard]\n\
597\n\
598Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
599all k, counting elements from 0. For the sake of comparison,\n\
600non-existing elements are considered to be infinite. The interesting\n\
601property of a heap is that a[0] is always its smallest element.\n"
602"\n\
603The strange invariant above is meant to be an efficient memory\n\
604representation for a tournament. The numbers below are `k', not a[k]:\n\
605\n\
606 0\n\
607\n\
608 1 2\n\
609\n\
610 3 4 5 6\n\
611\n\
612 7 8 9 10 11 12 13 14\n\
613\n\
614 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
615\n\
616\n\
617In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
618an usual binary tournament we see in sports, each cell is the winner\n\
619over the two cells it tops, and we can trace the winner down the tree\n\
620to see all opponents s/he had. However, in many computer applications\n\
621of such tournaments, we do not need to trace the history of a winner.\n\
622To be more memory efficient, when a winner is promoted, we try to\n\
623replace it by something else at a lower level, and the rule becomes\n\
624that a cell and the two cells it tops contain three different items,\n\
625but the top cell \"wins\" over the two topped cells.\n"
626"\n\
627If this heap invariant is protected at all time, index 0 is clearly\n\
628the overall winner. The simplest algorithmic way to remove it and\n\
629find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
630diagram above) into the 0 position, and then percolate this new 0 down\n\
631the tree, exchanging values, until the invariant is re-established.\n\
632This is clearly logarithmic on the total number of items in the tree.\n\
633By iterating over all items, you get an O(n ln n) sort.\n"
634"\n\
635A nice feature of this sort is that you can efficiently insert new\n\
636items while the sort is going on, provided that the inserted items are\n\
637not \"better\" than the last 0'th element you extracted. This is\n\
638especially useful in simulation contexts, where the tree holds all\n\
639incoming events, and the \"win\" condition means the smallest scheduled\n\
640time. When an event schedule other events for execution, they are\n\
641scheduled into the future, so they can easily go into the heap. So, a\n\
642heap is a good structure for implementing schedulers (this is what I\n\
643used for my MIDI sequencer :-).\n"
644"\n\
645Various structures for implementing schedulers have been extensively\n\
646studied, and heaps are good for this, as they are reasonably speedy,\n\
647the speed is almost constant, and the worst case is not much different\n\
648than the average case. However, there are other representations which\n\
649are more efficient overall, yet the worst cases might be terrible.\n"
650"\n\
651Heaps are also very useful in big disk sorts. You most probably all\n\
652know that a big sort implies producing \"runs\" (which are pre-sorted\n\
653sequences, which size is usually related to the amount of CPU memory),\n\
654followed by a merging passes for these runs, which merging is often\n\
655very cleverly organised[1]. It is very important that the initial\n\
656sort produces the longest runs possible. Tournaments are a good way\n\
657to that. If, using all the memory available to hold a tournament, you\n\
658replace and percolate items that happen to fit the current run, you'll\n\
659produce runs which are twice the size of the memory for random input,\n\
660and much better for input fuzzily ordered.\n"
661"\n\
662Moreover, if you output the 0'th item on disk and get an input which\n\
663may not fit in the current tournament (because the value \"wins\" over\n\
664the last output value), it cannot fit in the heap, so the size of the\n\
665heap decreases. The freed memory could be cleverly reused immediately\n\
666for progressively building a second heap, which grows at exactly the\n\
667same rate the first heap is melting. When the first heap completely\n\
668vanishes, you switch heaps and start a new run. Clever and quite\n\
669effective!\n\
670\n\
671In a word, heaps are useful memory structures to know. I use them in\n\
672a few applications, and I think it is good to keep a `heap' module\n\
673around. :-)\n"
674"\n\
675--------------------\n\
676[1] The disk balancing algorithms which are current, nowadays, are\n\
677more annoying than clever, and this is a consequence of the seeking\n\
678capabilities of the disks. On devices which cannot seek, like big\n\
679tape drives, the story was quite different, and one had to be very\n\
680clever to ensure (far in advance) that each tape movement will be the\n\
681most effective possible (that is, will best participate at\n\
682\"progressing\" the merge). Some tapes were even able to read\n\
683backwards, and this was also used to avoid the rewinding time.\n\
684Believe me, real good tape sorts were quite spectacular to watch!\n\
685From all times, sorting has always been a Great Art! :-)\n");
686
687PyMODINIT_FUNC
688init_heapq(void)
689{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 PyObject *m;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000691
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000692 m = Py_InitModule3("_heapq", heapq_methods, module_doc);
693 if (m == NULL)
694 return;
695 PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000696}
697