blob: ad190dfc034972e9dd0ef0b116f38db2dec9cd02 [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{
Raymond Hettinger871620d2014-05-03 18:36:48 -070014 PyObject *newitem, *parent;
Raymond Hettinger90e93382014-05-03 18:45:54 -070015 Py_ssize_t parentpos, size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016 int cmp;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018 assert(PyList_Check(heap));
Antoine Pitrou44d52142013-03-04 20:30:01 +010019 size = PyList_GET_SIZE(heap);
20 if (pos >= size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 PyErr_SetString(PyExc_IndexError, "index out of range");
22 return -1;
23 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 /* Follow the path to the root, moving parents down until finding
26 a place newitem fits. */
Raymond Hettinger871620d2014-05-03 18:36:48 -070027 newitem = PyList_GET_ITEM(heap, pos);
Raymond Hettinger90e93382014-05-03 18:45:54 -070028 while (pos > startpos) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 parentpos = (pos - 1) >> 1;
30 parent = PyList_GET_ITEM(heap, parentpos);
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000031 cmp = PyObject_RichCompareBool(newitem, parent, Py_LT);
Raymond Hettinger871620d2014-05-03 18:36:48 -070032 if (cmp == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return -1;
Antoine Pitrou44d52142013-03-04 20:30:01 +010034 if (size != PyList_GET_SIZE(heap)) {
Antoine Pitrou44d52142013-03-04 20:30:01 +010035 PyErr_SetString(PyExc_RuntimeError,
36 "list changed size during iteration");
37 return -1;
38 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 if (cmp == 0)
40 break;
Raymond Hettinger871620d2014-05-03 18:36:48 -070041 parent = PyList_GET_ITEM(heap, parentpos);
42 newitem = PyList_GET_ITEM(heap, pos);
43 PyList_SET_ITEM(heap, parentpos, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 PyList_SET_ITEM(heap, pos, parent);
45 pos = parentpos;
46 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return 0;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000048}
49
50static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +000051_siftup(PyListObject *heap, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000052{
Raymond Hettingerc9926082014-05-03 15:22:07 -070053 Py_ssize_t startpos, endpos, childpos, rightpos, limit;
Raymond Hettinger871620d2014-05-03 18:36:48 -070054 PyObject *tmp1, *tmp2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 int cmp;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 assert(PyList_Check(heap));
Raymond Hettinger871620d2014-05-03 18:36:48 -070058 endpos = PyList_GET_SIZE(heap);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 startpos = pos;
60 if (pos >= endpos) {
61 PyErr_SetString(PyExc_IndexError, "index out of range");
62 return -1;
63 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 /* Bubble up the smaller child until hitting a leaf. */
Raymond Hettingerc9926082014-05-03 15:22:07 -070066 limit = endpos / 2; /* smallest pos that has no child */
67 while (pos < limit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 /* Set childpos to index of smaller child. */
Raymond Hettingerc9926082014-05-03 15:22:07 -070069 childpos = 2*pos + 1; /* leftmost child position */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 rightpos = childpos + 1;
71 if (rightpos < endpos) {
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000072 cmp = PyObject_RichCompareBool(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyList_GET_ITEM(heap, childpos),
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000074 PyList_GET_ITEM(heap, rightpos),
75 Py_LT);
Raymond Hettinger871620d2014-05-03 18:36:48 -070076 if (cmp == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (cmp == 0)
79 childpos = rightpos;
Raymond Hettinger871620d2014-05-03 18:36:48 -070080 if (endpos != PyList_GET_SIZE(heap)) {
81 PyErr_SetString(PyExc_RuntimeError,
82 "list changed size during iteration");
83 return -1;
84 }
Antoine Pitrou44d52142013-03-04 20:30:01 +010085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 /* Move the smaller child up. */
Raymond Hettinger871620d2014-05-03 18:36:48 -070087 tmp1 = PyList_GET_ITEM(heap, childpos);
88 tmp2 = PyList_GET_ITEM(heap, pos);
89 PyList_SET_ITEM(heap, childpos, tmp2);
90 PyList_SET_ITEM(heap, pos, tmp1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 pos = childpos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 }
Raymond Hettinger871620d2014-05-03 18:36:48 -070093 /* Bubble it up to its final resting place (by sifting its parents down). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 return _siftdown(heap, startpos, pos);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000095}
96
97static PyObject *
98heappush(PyObject *self, PyObject *args)
99{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 PyObject *heap, *item;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
103 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 if (!PyList_Check(heap)) {
106 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
107 return NULL;
108 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (PyList_Append(heap, item) == -1)
111 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
114 return NULL;
115 Py_INCREF(Py_None);
116 return Py_None;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000117}
118
119PyDoc_STRVAR(heappush_doc,
Raymond Hettingerbd8f2902013-01-18 17:35:25 -0800120"heappush(heap, item) -> None. Push item onto heap, maintaining the heap invariant.");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000121
122static PyObject *
123heappop(PyObject *self, PyObject *heap)
124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyObject *lastelt, *returnitem;
126 Py_ssize_t n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 if (!PyList_Check(heap)) {
129 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
130 return NULL;
131 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 /* # raises appropriate IndexError if heap is empty */
134 n = PyList_GET_SIZE(heap);
135 if (n == 0) {
136 PyErr_SetString(PyExc_IndexError, "index out of range");
137 return NULL;
138 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 lastelt = PyList_GET_ITEM(heap, n-1) ;
141 Py_INCREF(lastelt);
Victor Stinner764a46d2013-07-17 21:50:21 +0200142 if (PyList_SetSlice(heap, n-1, n, NULL) < 0) {
143 Py_DECREF(lastelt);
144 return NULL;
145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 n--;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (!n)
149 return lastelt;
150 returnitem = PyList_GET_ITEM(heap, 0);
151 PyList_SET_ITEM(heap, 0, lastelt);
152 if (_siftup((PyListObject *)heap, 0) == -1) {
153 Py_DECREF(returnitem);
154 return NULL;
155 }
156 return returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000157}
158
159PyDoc_STRVAR(heappop_doc,
160"Pop the smallest item off the heap, maintaining the heap invariant.");
161
162static PyObject *
163heapreplace(PyObject *self, PyObject *args)
164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 PyObject *heap, *item, *returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
168 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 if (!PyList_Check(heap)) {
171 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
172 return NULL;
173 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (PyList_GET_SIZE(heap) < 1) {
176 PyErr_SetString(PyExc_IndexError, "index out of range");
177 return NULL;
178 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 returnitem = PyList_GET_ITEM(heap, 0);
181 Py_INCREF(item);
182 PyList_SET_ITEM(heap, 0, item);
183 if (_siftup((PyListObject *)heap, 0) == -1) {
184 Py_DECREF(returnitem);
185 return NULL;
186 }
187 return returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000188}
189
190PyDoc_STRVAR(heapreplace_doc,
Raymond Hettingerbd8f2902013-01-18 17:35:25 -0800191"heapreplace(heap, item) -> value. Pop and return the current smallest value, and add the new item.\n\
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000192\n\
193This is more efficient than heappop() followed by heappush(), and can be\n\
194more appropriate when using a fixed-size heap. Note that the value\n\
195returned may be larger than item! That constrains reasonable uses of\n\
Raymond Hettinger8158e842004-09-06 07:04:09 +0000196this routine unless written as part of a conditional replacement:\n\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 if item > heap[0]:\n\
198 item = heapreplace(heap, item)\n");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000199
200static PyObject *
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000201heappushpop(PyObject *self, PyObject *args)
202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 PyObject *heap, *item, *returnitem;
204 int cmp;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
207 return NULL;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (!PyList_Check(heap)) {
210 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
211 return NULL;
212 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if (PyList_GET_SIZE(heap) < 1) {
215 Py_INCREF(item);
216 return item;
217 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000218
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000219 cmp = PyObject_RichCompareBool(PyList_GET_ITEM(heap, 0), item, Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 if (cmp == -1)
221 return NULL;
222 if (cmp == 0) {
223 Py_INCREF(item);
224 return item;
225 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 returnitem = PyList_GET_ITEM(heap, 0);
228 Py_INCREF(item);
229 PyList_SET_ITEM(heap, 0, item);
230 if (_siftup((PyListObject *)heap, 0) == -1) {
231 Py_DECREF(returnitem);
232 return NULL;
233 }
234 return returnitem;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000235}
236
237PyDoc_STRVAR(heappushpop_doc,
Raymond Hettingerbd8f2902013-01-18 17:35:25 -0800238"heappushpop(heap, item) -> value. Push item on the heap, then pop and return the smallest item\n\
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000239from the heap. The combined action runs more efficiently than\n\
240heappush() followed by a separate call to heappop().");
241
242static PyObject *
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000243heapify(PyObject *self, PyObject *heap)
244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_ssize_t i, n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (!PyList_Check(heap)) {
248 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
249 return NULL;
250 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 n = PyList_GET_SIZE(heap);
253 /* Transform bottom-up. The largest index there's any point to
254 looking at is the largest with a child index in-range, so must
255 have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
256 (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
257 n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
258 and that's again n//2-1.
259 */
260 for (i=n/2-1 ; i>=0 ; i--)
261 if(_siftup((PyListObject *)heap, i) == -1)
262 return NULL;
263 Py_INCREF(Py_None);
264 return Py_None;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000265}
266
267PyDoc_STRVAR(heapify_doc,
268"Transform list into a heap, in-place, in O(len(heap)) time.");
269
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000270static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000271_siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 PyObject *newitem, *parent;
Raymond Hettinger90e93382014-05-03 18:45:54 -0700274 Py_ssize_t parentpos, size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 int cmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 assert(PyList_Check(heap));
Raymond Hettinger90e93382014-05-03 18:45:54 -0700278 size = PyList_GET_SIZE(heap);
279 if (pos >= size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyErr_SetString(PyExc_IndexError, "index out of range");
281 return -1;
282 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* Follow the path to the root, moving parents down until finding
285 a place newitem fits. */
Raymond Hettinger871620d2014-05-03 18:36:48 -0700286 newitem = PyList_GET_ITEM(heap, pos);
Raymond Hettinger90e93382014-05-03 18:45:54 -0700287 while (pos > startpos) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 parentpos = (pos - 1) >> 1;
289 parent = PyList_GET_ITEM(heap, parentpos);
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000290 cmp = PyObject_RichCompareBool(parent, newitem, Py_LT);
Raymond Hettinger871620d2014-05-03 18:36:48 -0700291 if (cmp == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return -1;
Raymond Hettinger90e93382014-05-03 18:45:54 -0700293 if (size != PyList_GET_SIZE(heap)) {
294 PyErr_SetString(PyExc_RuntimeError,
295 "list changed size during iteration");
296 return -1;
297 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (cmp == 0)
299 break;
Raymond Hettinger871620d2014-05-03 18:36:48 -0700300 parent = PyList_GET_ITEM(heap, parentpos);
301 newitem = PyList_GET_ITEM(heap, pos);
302 PyList_SET_ITEM(heap, parentpos, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 PyList_SET_ITEM(heap, pos, parent);
304 pos = parentpos;
305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 return 0;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000307}
308
309static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000310_siftupmax(PyListObject *heap, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000311{
Raymond Hettingerc9926082014-05-03 15:22:07 -0700312 Py_ssize_t startpos, endpos, childpos, rightpos, limit;
Raymond Hettinger871620d2014-05-03 18:36:48 -0700313 PyObject *tmp1, *tmp2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 int cmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 assert(PyList_Check(heap));
317 endpos = PyList_GET_SIZE(heap);
318 startpos = pos;
319 if (pos >= endpos) {
320 PyErr_SetString(PyExc_IndexError, "index out of range");
321 return -1;
322 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 /* Bubble up the smaller child until hitting a leaf. */
Raymond Hettingerc9926082014-05-03 15:22:07 -0700325 limit = endpos / 2; /* smallest pos that has no child */
326 while (pos < limit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* Set childpos to index of smaller child. */
Raymond Hettingerc9926082014-05-03 15:22:07 -0700328 childpos = 2*pos + 1; /* leftmost child position */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 rightpos = childpos + 1;
330 if (rightpos < endpos) {
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000331 cmp = PyObject_RichCompareBool(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyList_GET_ITEM(heap, rightpos),
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000333 PyList_GET_ITEM(heap, childpos),
334 Py_LT);
Raymond Hettinger871620d2014-05-03 18:36:48 -0700335 if (cmp == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (cmp == 0)
338 childpos = rightpos;
Raymond Hettinger871620d2014-05-03 18:36:48 -0700339 if (endpos != PyList_GET_SIZE(heap)) {
340 PyErr_SetString(PyExc_RuntimeError,
341 "list changed size during iteration");
342 return -1;
343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 }
345 /* Move the smaller child up. */
Raymond Hettinger871620d2014-05-03 18:36:48 -0700346 tmp1 = PyList_GET_ITEM(heap, childpos);
347 tmp2 = PyList_GET_ITEM(heap, pos);
348 PyList_SET_ITEM(heap, childpos, tmp2);
349 PyList_SET_ITEM(heap, pos, tmp1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 pos = childpos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 }
Raymond Hettinger871620d2014-05-03 18:36:48 -0700352 /* Bubble it up to its final resting place (by sifting its parents down). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 return _siftdownmax(heap, startpos, pos);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000354}
355
356static PyObject *
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700357_heapreplace_max(PyObject *self, PyObject *args)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000358{
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700359 PyObject *heap, *item, *returnitem;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000360
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700361 if (!PyArg_UnpackTuple(args, "_heapreplace_max", 2, 2, &heap, &item))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 return NULL;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000363
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700364 if (!PyList_Check(heap)) {
365 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000368
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700369 if (PyList_GET_SIZE(heap) < 1) {
370 PyErr_SetString(PyExc_IndexError, "index out of range");
371 return NULL;
372 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000373
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700374 returnitem = PyList_GET_ITEM(heap, 0);
375 Py_INCREF(item);
376 PyList_SET_ITEM(heap, 0, item);
377 if (_siftupmax((PyListObject *)heap, 0) == -1) {
378 Py_DECREF(returnitem);
379 return NULL;
380 }
381 return returnitem;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000382}
383
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700384PyDoc_STRVAR(heapreplace_max_doc, "Maxheap variant of heapreplace");
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000385
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000386static PyMethodDef heapq_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 {"heappush", (PyCFunction)heappush,
388 METH_VARARGS, heappush_doc},
389 {"heappushpop", (PyCFunction)heappushpop,
390 METH_VARARGS, heappushpop_doc},
391 {"heappop", (PyCFunction)heappop,
392 METH_O, heappop_doc},
393 {"heapreplace", (PyCFunction)heapreplace,
394 METH_VARARGS, heapreplace_doc},
395 {"heapify", (PyCFunction)heapify,
396 METH_O, heapify_doc},
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700397 {"_heapreplace_max",(PyCFunction)_heapreplace_max,
398 METH_VARARGS, heapreplace_max_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 {NULL, NULL} /* sentinel */
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000400};
401
402PyDoc_STRVAR(module_doc,
403"Heap queue algorithm (a.k.a. priority queue).\n\
404\n\
405Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
406all k, counting elements from 0. For the sake of comparison,\n\
407non-existing elements are considered to be infinite. The interesting\n\
408property of a heap is that a[0] is always its smallest element.\n\
409\n\
410Usage:\n\
411\n\
412heap = [] # creates an empty heap\n\
413heappush(heap, item) # pushes a new item on the heap\n\
414item = heappop(heap) # pops the smallest item from the heap\n\
415item = heap[0] # smallest item on the heap without popping it\n\
416heapify(x) # transforms list into a heap, in-place, in linear time\n\
417item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
418 # new item; the heap size is unchanged\n\
419\n\
420Our API differs from textbook heap algorithms as follows:\n\
421\n\
422- We use 0-based indexing. This makes the relationship between the\n\
423 index for a node and the indexes for its children slightly less\n\
424 obvious, but is more suitable since Python uses 0-based indexing.\n\
425\n\
426- Our heappop() method returns the smallest item, not the largest.\n\
427\n\
428These two make it possible to view the heap as a regular Python list\n\
429without surprises: heap[0] is the smallest item, and heap.sort()\n\
430maintains the heap invariant!\n");
431
432
433PyDoc_STRVAR(__about__,
434"Heap queues\n\
435\n\
Neal Norwitzc1786ea2007-08-23 23:58:43 +0000436[explanation by Fran\xc3\xa7ois Pinard]\n\
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000437\n\
438Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
439all k, counting elements from 0. For the sake of comparison,\n\
440non-existing elements are considered to be infinite. The interesting\n\
441property of a heap is that a[0] is always its smallest element.\n"
442"\n\
443The strange invariant above is meant to be an efficient memory\n\
444representation for a tournament. The numbers below are `k', not a[k]:\n\
445\n\
446 0\n\
447\n\
448 1 2\n\
449\n\
450 3 4 5 6\n\
451\n\
452 7 8 9 10 11 12 13 14\n\
453\n\
454 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
455\n\
456\n\
457In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
458an usual binary tournament we see in sports, each cell is the winner\n\
459over the two cells it tops, and we can trace the winner down the tree\n\
460to see all opponents s/he had. However, in many computer applications\n\
461of such tournaments, we do not need to trace the history of a winner.\n\
462To be more memory efficient, when a winner is promoted, we try to\n\
463replace it by something else at a lower level, and the rule becomes\n\
464that a cell and the two cells it tops contain three different items,\n\
465but the top cell \"wins\" over the two topped cells.\n"
466"\n\
467If this heap invariant is protected at all time, index 0 is clearly\n\
468the overall winner. The simplest algorithmic way to remove it and\n\
469find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
470diagram above) into the 0 position, and then percolate this new 0 down\n\
471the tree, exchanging values, until the invariant is re-established.\n\
472This is clearly logarithmic on the total number of items in the tree.\n\
473By iterating over all items, you get an O(n ln n) sort.\n"
474"\n\
475A nice feature of this sort is that you can efficiently insert new\n\
476items while the sort is going on, provided that the inserted items are\n\
477not \"better\" than the last 0'th element you extracted. This is\n\
478especially useful in simulation contexts, where the tree holds all\n\
479incoming events, and the \"win\" condition means the smallest scheduled\n\
480time. When an event schedule other events for execution, they are\n\
481scheduled into the future, so they can easily go into the heap. So, a\n\
482heap is a good structure for implementing schedulers (this is what I\n\
483used for my MIDI sequencer :-).\n"
484"\n\
485Various structures for implementing schedulers have been extensively\n\
486studied, and heaps are good for this, as they are reasonably speedy,\n\
487the speed is almost constant, and the worst case is not much different\n\
488than the average case. However, there are other representations which\n\
489are more efficient overall, yet the worst cases might be terrible.\n"
490"\n\
491Heaps are also very useful in big disk sorts. You most probably all\n\
492know that a big sort implies producing \"runs\" (which are pre-sorted\n\
493sequences, which size is usually related to the amount of CPU memory),\n\
494followed by a merging passes for these runs, which merging is often\n\
495very cleverly organised[1]. It is very important that the initial\n\
496sort produces the longest runs possible. Tournaments are a good way\n\
497to that. If, using all the memory available to hold a tournament, you\n\
498replace and percolate items that happen to fit the current run, you'll\n\
499produce runs which are twice the size of the memory for random input,\n\
500and much better for input fuzzily ordered.\n"
501"\n\
502Moreover, if you output the 0'th item on disk and get an input which\n\
503may not fit in the current tournament (because the value \"wins\" over\n\
504the last output value), it cannot fit in the heap, so the size of the\n\
505heap decreases. The freed memory could be cleverly reused immediately\n\
506for progressively building a second heap, which grows at exactly the\n\
507same rate the first heap is melting. When the first heap completely\n\
508vanishes, you switch heaps and start a new run. Clever and quite\n\
509effective!\n\
510\n\
511In a word, heaps are useful memory structures to know. I use them in\n\
512a few applications, and I think it is good to keep a `heap' module\n\
513around. :-)\n"
514"\n\
515--------------------\n\
516[1] The disk balancing algorithms which are current, nowadays, are\n\
517more annoying than clever, and this is a consequence of the seeking\n\
518capabilities of the disks. On devices which cannot seek, like big\n\
519tape drives, the story was quite different, and one had to be very\n\
520clever to ensure (far in advance) that each tape movement will be the\n\
521most effective possible (that is, will best participate at\n\
522\"progressing\" the merge). Some tapes were even able to read\n\
523backwards, and this was also used to avoid the rewinding time.\n\
524Believe me, real good tape sorts were quite spectacular to watch!\n\
525From all times, sorting has always been a Great Art! :-)\n");
526
Martin v. Löwis1a214512008-06-11 05:26:20 +0000527
528static struct PyModuleDef _heapqmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 PyModuleDef_HEAD_INIT,
530 "_heapq",
531 module_doc,
532 -1,
533 heapq_methods,
534 NULL,
535 NULL,
536 NULL,
537 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000538};
539
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000540PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000541PyInit__heapq(void)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 PyObject *m, *about;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 m = PyModule_Create(&_heapqmodule);
546 if (m == NULL)
547 return NULL;
548 about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL);
549 PyModule_AddObject(m, "__about__", about);
550 return m;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000551}
552