blob: 361cf553160e3cd9107ebd7ff8f39e665383e0da [file] [log] [blame]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Araujo1670b432010-09-03 22:03:10 +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
Georg Brandlf78e02b2008-06-10 17:40:04 +000011static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +000012_siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000013{
Antoine Pitrou44d52142013-03-04 20:30:01 +010014 PyObject *newitem, *parent, *olditem;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000015 int cmp;
16 Py_ssize_t parentpos;
Antoine Pitrou44d52142013-03-04 20:30:01 +010017 Py_ssize_t size;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019 assert(PyList_Check(heap));
Antoine Pitrou44d52142013-03-04 20:30:01 +010020 size = PyList_GET_SIZE(heap);
21 if (pos >= size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 PyErr_SetString(PyExc_IndexError, "index out of range");
23 return -1;
24 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 newitem = PyList_GET_ITEM(heap, pos);
27 Py_INCREF(newitem);
28 /* Follow the path to the root, moving parents down until finding
29 a place newitem fits. */
30 while (pos > startpos){
31 parentpos = (pos - 1) >> 1;
32 parent = PyList_GET_ITEM(heap, parentpos);
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000033 cmp = PyObject_RichCompareBool(newitem, parent, Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 if (cmp == -1) {
35 Py_DECREF(newitem);
36 return -1;
37 }
Antoine Pitrou44d52142013-03-04 20:30:01 +010038 if (size != PyList_GET_SIZE(heap)) {
39 Py_DECREF(newitem);
40 PyErr_SetString(PyExc_RuntimeError,
41 "list changed size during iteration");
42 return -1;
43 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 if (cmp == 0)
45 break;
46 Py_INCREF(parent);
Antoine Pitrou44d52142013-03-04 20:30:01 +010047 olditem = PyList_GET_ITEM(heap, pos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 PyList_SET_ITEM(heap, pos, parent);
Antoine Pitrou44d52142013-03-04 20:30:01 +010049 Py_DECREF(olditem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 pos = parentpos;
Antoine Pitrou44d52142013-03-04 20:30:01 +010051 if (size != PyList_GET_SIZE(heap)) {
52 PyErr_SetString(PyExc_RuntimeError,
53 "list changed size during iteration");
54 return -1;
55 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 }
57 Py_DECREF(PyList_GET_ITEM(heap, pos));
58 PyList_SET_ITEM(heap, pos, newitem);
59 return 0;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000060}
61
62static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +000063_siftup(PyListObject *heap, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 Py_ssize_t startpos, endpos, childpos, rightpos;
66 int cmp;
Antoine Pitrou44d52142013-03-04 20:30:01 +010067 PyObject *newitem, *tmp, *olditem;
68 Py_ssize_t size;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 assert(PyList_Check(heap));
Antoine Pitrou44d52142013-03-04 20:30:01 +010071 size = PyList_GET_SIZE(heap);
72 endpos = size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 startpos = pos;
74 if (pos >= endpos) {
75 PyErr_SetString(PyExc_IndexError, "index out of range");
76 return -1;
77 }
78 newitem = PyList_GET_ITEM(heap, pos);
79 Py_INCREF(newitem);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 /* Bubble up the smaller child until hitting a leaf. */
82 childpos = 2*pos + 1; /* leftmost child position */
83 while (childpos < endpos) {
84 /* Set childpos to index of smaller child. */
85 rightpos = childpos + 1;
86 if (rightpos < endpos) {
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000087 cmp = PyObject_RichCompareBool(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 PyList_GET_ITEM(heap, childpos),
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000089 PyList_GET_ITEM(heap, rightpos),
90 Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 if (cmp == -1) {
92 Py_DECREF(newitem);
93 return -1;
94 }
95 if (cmp == 0)
96 childpos = rightpos;
97 }
Antoine Pitrou44d52142013-03-04 20:30:01 +010098 if (size != PyList_GET_SIZE(heap)) {
99 Py_DECREF(newitem);
100 PyErr_SetString(PyExc_RuntimeError,
101 "list changed size during iteration");
102 return -1;
103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 /* Move the smaller child up. */
105 tmp = PyList_GET_ITEM(heap, childpos);
106 Py_INCREF(tmp);
Antoine Pitrou44d52142013-03-04 20:30:01 +0100107 olditem = PyList_GET_ITEM(heap, pos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 PyList_SET_ITEM(heap, pos, tmp);
Antoine Pitrou44d52142013-03-04 20:30:01 +0100109 Py_DECREF(olditem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 pos = childpos;
111 childpos = 2*pos + 1;
Antoine Pitrou44d52142013-03-04 20:30:01 +0100112 if (size != PyList_GET_SIZE(heap)) {
113 PyErr_SetString(PyExc_RuntimeError,
114 "list changed size during iteration");
115 return -1;
116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 /* The leaf at pos is empty now. Put newitem there, and and bubble
120 it up to its final resting place (by sifting its parents down). */
121 Py_DECREF(PyList_GET_ITEM(heap, pos));
122 PyList_SET_ITEM(heap, pos, newitem);
123 return _siftdown(heap, startpos, pos);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000124}
125
126static PyObject *
127heappush(PyObject *self, PyObject *args)
128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 PyObject *heap, *item;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
132 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (!PyList_Check(heap)) {
135 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
136 return NULL;
137 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 if (PyList_Append(heap, item) == -1)
140 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
143 return NULL;
144 Py_INCREF(Py_None);
145 return Py_None;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000146}
147
148PyDoc_STRVAR(heappush_doc,
149"Push item onto heap, maintaining the heap invariant.");
150
151static PyObject *
152heappop(PyObject *self, PyObject *heap)
153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 PyObject *lastelt, *returnitem;
155 Py_ssize_t n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 if (!PyList_Check(heap)) {
158 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
159 return NULL;
160 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* # raises appropriate IndexError if heap is empty */
163 n = PyList_GET_SIZE(heap);
164 if (n == 0) {
165 PyErr_SetString(PyExc_IndexError, "index out of range");
166 return NULL;
167 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 lastelt = PyList_GET_ITEM(heap, n-1) ;
170 Py_INCREF(lastelt);
171 PyList_SetSlice(heap, n-1, n, NULL);
172 n--;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (!n)
175 return lastelt;
176 returnitem = PyList_GET_ITEM(heap, 0);
177 PyList_SET_ITEM(heap, 0, lastelt);
178 if (_siftup((PyListObject *)heap, 0) == -1) {
179 Py_DECREF(returnitem);
180 return NULL;
181 }
182 return returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000183}
184
185PyDoc_STRVAR(heappop_doc,
186"Pop the smallest item off the heap, maintaining the heap invariant.");
187
188static PyObject *
189heapreplace(PyObject *self, PyObject *args)
190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 PyObject *heap, *item, *returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
194 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 if (!PyList_Check(heap)) {
197 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
198 return NULL;
199 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (PyList_GET_SIZE(heap) < 1) {
202 PyErr_SetString(PyExc_IndexError, "index out of range");
203 return NULL;
204 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 returnitem = PyList_GET_ITEM(heap, 0);
207 Py_INCREF(item);
208 PyList_SET_ITEM(heap, 0, item);
209 if (_siftup((PyListObject *)heap, 0) == -1) {
210 Py_DECREF(returnitem);
211 return NULL;
212 }
213 return returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000214}
215
216PyDoc_STRVAR(heapreplace_doc,
217"Pop and return the current smallest value, and add the new item.\n\
218\n\
219This is more efficient than heappop() followed by heappush(), and can be\n\
220more appropriate when using a fixed-size heap. Note that the value\n\
221returned may be larger than item! That constrains reasonable uses of\n\
Raymond Hettinger8158e842004-09-06 07:04:09 +0000222this routine unless written as part of a conditional replacement:\n\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if item > heap[0]:\n\
224 item = heapreplace(heap, item)\n");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000225
226static PyObject *
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000227heappushpop(PyObject *self, PyObject *args)
228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyObject *heap, *item, *returnitem;
230 int cmp;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
233 return NULL;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (!PyList_Check(heap)) {
236 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
237 return NULL;
238 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (PyList_GET_SIZE(heap) < 1) {
241 Py_INCREF(item);
242 return item;
243 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000244
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000245 cmp = PyObject_RichCompareBool(PyList_GET_ITEM(heap, 0), item, Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (cmp == -1)
247 return NULL;
248 if (cmp == 0) {
249 Py_INCREF(item);
250 return item;
251 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 returnitem = PyList_GET_ITEM(heap, 0);
254 Py_INCREF(item);
255 PyList_SET_ITEM(heap, 0, item);
256 if (_siftup((PyListObject *)heap, 0) == -1) {
257 Py_DECREF(returnitem);
258 return NULL;
259 }
260 return returnitem;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000261}
262
263PyDoc_STRVAR(heappushpop_doc,
264"Push item on the heap, then pop and return the smallest item\n\
265from the heap. The combined action runs more efficiently than\n\
266heappush() followed by a separate call to heappop().");
267
268static PyObject *
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000269heapify(PyObject *self, PyObject *heap)
270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 Py_ssize_t i, n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (!PyList_Check(heap)) {
274 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
275 return NULL;
276 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 n = PyList_GET_SIZE(heap);
279 /* Transform bottom-up. The largest index there's any point to
280 looking at is the largest with a child index in-range, so must
281 have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
282 (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
283 n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
284 and that's again n//2-1.
285 */
286 for (i=n/2-1 ; i>=0 ; i--)
287 if(_siftup((PyListObject *)heap, i) == -1)
288 return NULL;
289 Py_INCREF(Py_None);
290 return Py_None;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000291}
292
293PyDoc_STRVAR(heapify_doc,
294"Transform list into a heap, in-place, in O(len(heap)) time.");
295
Raymond Hettingerc9297662004-06-12 22:48:46 +0000296static PyObject *
297nlargest(PyObject *self, PyObject *args)
298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
300 Py_ssize_t i, n;
301 int cmp;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
304 return NULL;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 it = PyObject_GetIter(iterable);
307 if (it == NULL)
308 return NULL;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 heap = PyList_New(0);
311 if (heap == NULL)
312 goto fail;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 for (i=0 ; i<n ; i++ ){
315 elem = PyIter_Next(it);
316 if (elem == NULL) {
317 if (PyErr_Occurred())
318 goto fail;
319 else
320 goto sortit;
321 }
322 if (PyList_Append(heap, elem) == -1) {
323 Py_DECREF(elem);
324 goto fail;
325 }
326 Py_DECREF(elem);
327 }
328 if (PyList_GET_SIZE(heap) == 0)
329 goto sortit;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 for (i=n/2-1 ; i>=0 ; i--)
332 if(_siftup((PyListObject *)heap, i) == -1)
333 goto fail;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 sol = PyList_GET_ITEM(heap, 0);
336 while (1) {
337 elem = PyIter_Next(it);
338 if (elem == NULL) {
339 if (PyErr_Occurred())
340 goto fail;
341 else
342 goto sortit;
343 }
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000344 cmp = PyObject_RichCompareBool(sol, elem, Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 if (cmp == -1) {
346 Py_DECREF(elem);
347 goto fail;
348 }
349 if (cmp == 0) {
350 Py_DECREF(elem);
351 continue;
352 }
353 oldelem = PyList_GET_ITEM(heap, 0);
354 PyList_SET_ITEM(heap, 0, elem);
355 Py_DECREF(oldelem);
356 if (_siftup((PyListObject *)heap, 0) == -1)
357 goto fail;
358 sol = PyList_GET_ITEM(heap, 0);
359 }
Raymond Hettingerc9297662004-06-12 22:48:46 +0000360sortit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 if (PyList_Sort(heap) == -1)
362 goto fail;
363 if (PyList_Reverse(heap) == -1)
364 goto fail;
365 Py_DECREF(it);
366 return heap;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000367
368fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 Py_DECREF(it);
370 Py_XDECREF(heap);
371 return NULL;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000372}
373
374PyDoc_STRVAR(nlargest_doc,
375"Find the n largest elements in a dataset.\n\
376\n\
377Equivalent to: sorted(iterable, reverse=True)[:n]\n");
378
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000379static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000380_siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 PyObject *newitem, *parent;
383 int cmp;
384 Py_ssize_t parentpos;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 assert(PyList_Check(heap));
387 if (pos >= PyList_GET_SIZE(heap)) {
388 PyErr_SetString(PyExc_IndexError, "index out of range");
389 return -1;
390 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 newitem = PyList_GET_ITEM(heap, pos);
393 Py_INCREF(newitem);
394 /* Follow the path to the root, moving parents down until finding
395 a place newitem fits. */
396 while (pos > startpos){
397 parentpos = (pos - 1) >> 1;
398 parent = PyList_GET_ITEM(heap, parentpos);
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000399 cmp = PyObject_RichCompareBool(parent, newitem, Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 if (cmp == -1) {
401 Py_DECREF(newitem);
402 return -1;
403 }
404 if (cmp == 0)
405 break;
406 Py_INCREF(parent);
407 Py_DECREF(PyList_GET_ITEM(heap, pos));
408 PyList_SET_ITEM(heap, pos, parent);
409 pos = parentpos;
410 }
411 Py_DECREF(PyList_GET_ITEM(heap, pos));
412 PyList_SET_ITEM(heap, pos, newitem);
413 return 0;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000414}
415
416static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000417_siftupmax(PyListObject *heap, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 Py_ssize_t startpos, endpos, childpos, rightpos;
420 int cmp;
421 PyObject *newitem, *tmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 assert(PyList_Check(heap));
424 endpos = PyList_GET_SIZE(heap);
425 startpos = pos;
426 if (pos >= endpos) {
427 PyErr_SetString(PyExc_IndexError, "index out of range");
428 return -1;
429 }
430 newitem = PyList_GET_ITEM(heap, pos);
431 Py_INCREF(newitem);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 /* Bubble up the smaller child until hitting a leaf. */
434 childpos = 2*pos + 1; /* leftmost child position */
435 while (childpos < endpos) {
436 /* Set childpos to index of smaller child. */
437 rightpos = childpos + 1;
438 if (rightpos < endpos) {
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000439 cmp = PyObject_RichCompareBool(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 PyList_GET_ITEM(heap, rightpos),
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000441 PyList_GET_ITEM(heap, childpos),
442 Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (cmp == -1) {
444 Py_DECREF(newitem);
445 return -1;
446 }
447 if (cmp == 0)
448 childpos = rightpos;
449 }
450 /* Move the smaller child up. */
451 tmp = PyList_GET_ITEM(heap, childpos);
452 Py_INCREF(tmp);
453 Py_DECREF(PyList_GET_ITEM(heap, pos));
454 PyList_SET_ITEM(heap, pos, tmp);
455 pos = childpos;
456 childpos = 2*pos + 1;
457 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 /* The leaf at pos is empty now. Put newitem there, and and bubble
460 it up to its final resting place (by sifting its parents down). */
461 Py_DECREF(PyList_GET_ITEM(heap, pos));
462 PyList_SET_ITEM(heap, pos, newitem);
463 return _siftdownmax(heap, startpos, pos);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000464}
465
466static PyObject *
467nsmallest(PyObject *self, PyObject *args)
468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
470 Py_ssize_t i, n;
471 int cmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
474 return NULL;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 it = PyObject_GetIter(iterable);
477 if (it == NULL)
478 return NULL;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 heap = PyList_New(0);
481 if (heap == NULL)
482 goto fail;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 for (i=0 ; i<n ; i++ ){
485 elem = PyIter_Next(it);
486 if (elem == NULL) {
487 if (PyErr_Occurred())
488 goto fail;
489 else
490 goto sortit;
491 }
492 if (PyList_Append(heap, elem) == -1) {
493 Py_DECREF(elem);
494 goto fail;
495 }
496 Py_DECREF(elem);
497 }
498 n = PyList_GET_SIZE(heap);
499 if (n == 0)
500 goto sortit;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 for (i=n/2-1 ; i>=0 ; i--)
503 if(_siftupmax((PyListObject *)heap, i) == -1)
504 goto fail;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 los = PyList_GET_ITEM(heap, 0);
507 while (1) {
508 elem = PyIter_Next(it);
509 if (elem == NULL) {
510 if (PyErr_Occurred())
511 goto fail;
512 else
513 goto sortit;
514 }
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000515 cmp = PyObject_RichCompareBool(elem, los, Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (cmp == -1) {
517 Py_DECREF(elem);
518 goto fail;
519 }
520 if (cmp == 0) {
521 Py_DECREF(elem);
522 continue;
523 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 oldelem = PyList_GET_ITEM(heap, 0);
526 PyList_SET_ITEM(heap, 0, elem);
527 Py_DECREF(oldelem);
528 if (_siftupmax((PyListObject *)heap, 0) == -1)
529 goto fail;
530 los = PyList_GET_ITEM(heap, 0);
531 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000532
533sortit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (PyList_Sort(heap) == -1)
535 goto fail;
536 Py_DECREF(it);
537 return heap;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000538
539fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 Py_DECREF(it);
541 Py_XDECREF(heap);
542 return NULL;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000543}
544
545PyDoc_STRVAR(nsmallest_doc,
546"Find the n smallest elements in a dataset.\n\
547\n\
548Equivalent to: sorted(iterable)[:n]\n");
549
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000550static PyMethodDef heapq_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 {"heappush", (PyCFunction)heappush,
552 METH_VARARGS, heappush_doc},
553 {"heappushpop", (PyCFunction)heappushpop,
554 METH_VARARGS, heappushpop_doc},
555 {"heappop", (PyCFunction)heappop,
556 METH_O, heappop_doc},
557 {"heapreplace", (PyCFunction)heapreplace,
558 METH_VARARGS, heapreplace_doc},
559 {"heapify", (PyCFunction)heapify,
560 METH_O, heapify_doc},
561 {"nlargest", (PyCFunction)nlargest,
562 METH_VARARGS, nlargest_doc},
563 {"nsmallest", (PyCFunction)nsmallest,
564 METH_VARARGS, nsmallest_doc},
565 {NULL, NULL} /* sentinel */
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000566};
567
568PyDoc_STRVAR(module_doc,
569"Heap queue algorithm (a.k.a. priority queue).\n\
570\n\
571Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
572all k, counting elements from 0. For the sake of comparison,\n\
573non-existing elements are considered to be infinite. The interesting\n\
574property of a heap is that a[0] is always its smallest element.\n\
575\n\
576Usage:\n\
577\n\
578heap = [] # creates an empty heap\n\
579heappush(heap, item) # pushes a new item on the heap\n\
580item = heappop(heap) # pops the smallest item from the heap\n\
581item = heap[0] # smallest item on the heap without popping it\n\
582heapify(x) # transforms list into a heap, in-place, in linear time\n\
583item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
584 # new item; the heap size is unchanged\n\
585\n\
586Our API differs from textbook heap algorithms as follows:\n\
587\n\
588- We use 0-based indexing. This makes the relationship between the\n\
589 index for a node and the indexes for its children slightly less\n\
590 obvious, but is more suitable since Python uses 0-based indexing.\n\
591\n\
592- Our heappop() method returns the smallest item, not the largest.\n\
593\n\
594These two make it possible to view the heap as a regular Python list\n\
595without surprises: heap[0] is the smallest item, and heap.sort()\n\
596maintains the heap invariant!\n");
597
598
599PyDoc_STRVAR(__about__,
600"Heap queues\n\
601\n\
Neal Norwitzc1786ea2007-08-23 23:58:43 +0000602[explanation by Fran\xc3\xa7ois Pinard]\n\
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000603\n\
604Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
605all k, counting elements from 0. For the sake of comparison,\n\
606non-existing elements are considered to be infinite. The interesting\n\
607property of a heap is that a[0] is always its smallest element.\n"
608"\n\
609The strange invariant above is meant to be an efficient memory\n\
610representation for a tournament. The numbers below are `k', not a[k]:\n\
611\n\
612 0\n\
613\n\
614 1 2\n\
615\n\
616 3 4 5 6\n\
617\n\
618 7 8 9 10 11 12 13 14\n\
619\n\
620 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
621\n\
622\n\
623In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
624an usual binary tournament we see in sports, each cell is the winner\n\
625over the two cells it tops, and we can trace the winner down the tree\n\
626to see all opponents s/he had. However, in many computer applications\n\
627of such tournaments, we do not need to trace the history of a winner.\n\
628To be more memory efficient, when a winner is promoted, we try to\n\
629replace it by something else at a lower level, and the rule becomes\n\
630that a cell and the two cells it tops contain three different items,\n\
631but the top cell \"wins\" over the two topped cells.\n"
632"\n\
633If this heap invariant is protected at all time, index 0 is clearly\n\
634the overall winner. The simplest algorithmic way to remove it and\n\
635find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
636diagram above) into the 0 position, and then percolate this new 0 down\n\
637the tree, exchanging values, until the invariant is re-established.\n\
638This is clearly logarithmic on the total number of items in the tree.\n\
639By iterating over all items, you get an O(n ln n) sort.\n"
640"\n\
641A nice feature of this sort is that you can efficiently insert new\n\
642items while the sort is going on, provided that the inserted items are\n\
643not \"better\" than the last 0'th element you extracted. This is\n\
644especially useful in simulation contexts, where the tree holds all\n\
645incoming events, and the \"win\" condition means the smallest scheduled\n\
646time. When an event schedule other events for execution, they are\n\
647scheduled into the future, so they can easily go into the heap. So, a\n\
648heap is a good structure for implementing schedulers (this is what I\n\
649used for my MIDI sequencer :-).\n"
650"\n\
651Various structures for implementing schedulers have been extensively\n\
652studied, and heaps are good for this, as they are reasonably speedy,\n\
653the speed is almost constant, and the worst case is not much different\n\
654than the average case. However, there are other representations which\n\
655are more efficient overall, yet the worst cases might be terrible.\n"
656"\n\
657Heaps are also very useful in big disk sorts. You most probably all\n\
658know that a big sort implies producing \"runs\" (which are pre-sorted\n\
659sequences, which size is usually related to the amount of CPU memory),\n\
660followed by a merging passes for these runs, which merging is often\n\
661very cleverly organised[1]. It is very important that the initial\n\
662sort produces the longest runs possible. Tournaments are a good way\n\
663to that. If, using all the memory available to hold a tournament, you\n\
664replace and percolate items that happen to fit the current run, you'll\n\
665produce runs which are twice the size of the memory for random input,\n\
666and much better for input fuzzily ordered.\n"
667"\n\
668Moreover, if you output the 0'th item on disk and get an input which\n\
669may not fit in the current tournament (because the value \"wins\" over\n\
670the last output value), it cannot fit in the heap, so the size of the\n\
671heap decreases. The freed memory could be cleverly reused immediately\n\
672for progressively building a second heap, which grows at exactly the\n\
673same rate the first heap is melting. When the first heap completely\n\
674vanishes, you switch heaps and start a new run. Clever and quite\n\
675effective!\n\
676\n\
677In a word, heaps are useful memory structures to know. I use them in\n\
678a few applications, and I think it is good to keep a `heap' module\n\
679around. :-)\n"
680"\n\
681--------------------\n\
682[1] The disk balancing algorithms which are current, nowadays, are\n\
683more annoying than clever, and this is a consequence of the seeking\n\
684capabilities of the disks. On devices which cannot seek, like big\n\
685tape drives, the story was quite different, and one had to be very\n\
686clever to ensure (far in advance) that each tape movement will be the\n\
687most effective possible (that is, will best participate at\n\
688\"progressing\" the merge). Some tapes were even able to read\n\
689backwards, and this was also used to avoid the rewinding time.\n\
690Believe me, real good tape sorts were quite spectacular to watch!\n\
691From all times, sorting has always been a Great Art! :-)\n");
692
Martin v. Löwis1a214512008-06-11 05:26:20 +0000693
694static struct PyModuleDef _heapqmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 PyModuleDef_HEAD_INIT,
696 "_heapq",
697 module_doc,
698 -1,
699 heapq_methods,
700 NULL,
701 NULL,
702 NULL,
703 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000704};
705
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000706PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000707PyInit__heapq(void)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyObject *m, *about;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 m = PyModule_Create(&_heapqmodule);
712 if (m == NULL)
713 return NULL;
714 about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL);
715 PyModule_AddObject(m, "__about__", about);
716 return m;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000717}
718