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