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