Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +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 | |
Neal Norwitz | 9342fb4 | 2003-12-13 22:31:53 +0000 | [diff] [blame] | 11 | static int |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 12 | _siftdown(PyListObject *heap, int startpos, int pos) |
| 13 | { |
| 14 | PyObject *newitem, *parent; |
| 15 | int cmp, parentpos; |
| 16 | |
Raymond Hettinger | 6dab052 | 2003-11-15 12:40:28 +0000 | [diff] [blame] | 17 | assert(PyList_Check(heap)); |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 18 | if (pos >= PyList_GET_SIZE(heap)) { |
| 19 | PyErr_SetString(PyExc_IndexError, "index out of range"); |
| 20 | return -1; |
| 21 | } |
| 22 | |
| 23 | newitem = PyList_GET_ITEM(heap, pos); |
| 24 | Py_INCREF(newitem); |
| 25 | /* Follow the path to the root, moving parents down until finding |
| 26 | a place newitem fits. */ |
| 27 | while (pos > startpos){ |
| 28 | parentpos = (pos - 1) >> 1; |
| 29 | parent = PyList_GET_ITEM(heap, parentpos); |
| 30 | cmp = PyObject_RichCompareBool(parent, newitem, Py_LE); |
| 31 | if (cmp == -1) |
| 32 | return -1; |
| 33 | if (cmp == 1) |
| 34 | break; |
| 35 | Py_INCREF(parent); |
| 36 | Py_DECREF(PyList_GET_ITEM(heap, pos)); |
| 37 | PyList_SET_ITEM(heap, pos, parent); |
| 38 | pos = parentpos; |
| 39 | } |
| 40 | Py_DECREF(PyList_GET_ITEM(heap, pos)); |
| 41 | PyList_SET_ITEM(heap, pos, newitem); |
| 42 | return 0; |
| 43 | } |
| 44 | |
Neal Norwitz | 9342fb4 | 2003-12-13 22:31:53 +0000 | [diff] [blame] | 45 | static int |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 46 | _siftup(PyListObject *heap, int pos) |
| 47 | { |
| 48 | int startpos, endpos, childpos, rightpos; |
| 49 | int cmp; |
| 50 | PyObject *newitem, *tmp; |
| 51 | |
Raymond Hettinger | 6dab052 | 2003-11-15 12:40:28 +0000 | [diff] [blame] | 52 | assert(PyList_Check(heap)); |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 53 | endpos = PyList_GET_SIZE(heap); |
| 54 | startpos = pos; |
| 55 | if (pos >= endpos) { |
| 56 | PyErr_SetString(PyExc_IndexError, "index out of range"); |
| 57 | return -1; |
| 58 | } |
| 59 | newitem = PyList_GET_ITEM(heap, pos); |
| 60 | Py_INCREF(newitem); |
| 61 | |
| 62 | /* Bubble up the smaller child until hitting a leaf. */ |
| 63 | childpos = 2*pos + 1; /* leftmost child position */ |
| 64 | while (childpos < endpos) { |
| 65 | /* Set childpos to index of smaller child. */ |
| 66 | rightpos = childpos + 1; |
| 67 | if (rightpos < endpos) { |
| 68 | cmp = PyObject_RichCompareBool( |
| 69 | PyList_GET_ITEM(heap, rightpos), |
| 70 | PyList_GET_ITEM(heap, childpos), |
| 71 | Py_LE); |
| 72 | if (cmp == -1) |
| 73 | return -1; |
| 74 | if (cmp == 1) |
| 75 | childpos = rightpos; |
| 76 | } |
| 77 | /* Move the smaller child up. */ |
| 78 | tmp = PyList_GET_ITEM(heap, childpos); |
| 79 | Py_INCREF(tmp); |
| 80 | Py_DECREF(PyList_GET_ITEM(heap, pos)); |
| 81 | PyList_SET_ITEM(heap, pos, tmp); |
| 82 | pos = childpos; |
| 83 | childpos = 2*pos + 1; |
| 84 | } |
| 85 | |
| 86 | /* The leaf at pos is empty now. Put newitem there, and and bubble |
| 87 | it up to its final resting place (by sifting its parents down). */ |
| 88 | Py_DECREF(PyList_GET_ITEM(heap, pos)); |
| 89 | PyList_SET_ITEM(heap, pos, newitem); |
| 90 | return _siftdown(heap, startpos, pos); |
| 91 | } |
| 92 | |
Neal Norwitz | 9342fb4 | 2003-12-13 22:31:53 +0000 | [diff] [blame] | 93 | static PyObject * |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 94 | heappush(PyObject *self, PyObject *args) |
| 95 | { |
| 96 | PyObject *heap, *item; |
| 97 | |
| 98 | if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item)) |
| 99 | return NULL; |
| 100 | |
| 101 | if (!PyList_Check(heap)) { |
Raymond Hettinger | 6dab052 | 2003-11-15 12:40:28 +0000 | [diff] [blame] | 102 | PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 103 | return NULL; |
| 104 | } |
| 105 | |
| 106 | if (PyList_Append(heap, item) == -1) |
| 107 | return NULL; |
| 108 | |
| 109 | if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1) |
| 110 | return NULL; |
| 111 | Py_INCREF(Py_None); |
| 112 | return Py_None; |
| 113 | } |
| 114 | |
| 115 | PyDoc_STRVAR(heappush_doc, |
| 116 | "Push item onto heap, maintaining the heap invariant."); |
| 117 | |
Neal Norwitz | 9342fb4 | 2003-12-13 22:31:53 +0000 | [diff] [blame] | 118 | static PyObject * |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 119 | heappop(PyObject *self, PyObject *heap) |
| 120 | { |
| 121 | PyObject *lastelt, *returnitem; |
| 122 | int n; |
| 123 | |
Raymond Hettinger | 236a244 | 2003-11-15 12:33:01 +0000 | [diff] [blame] | 124 | if (!PyList_Check(heap)) { |
Raymond Hettinger | 6dab052 | 2003-11-15 12:40:28 +0000 | [diff] [blame] | 125 | PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); |
Raymond Hettinger | 236a244 | 2003-11-15 12:33:01 +0000 | [diff] [blame] | 126 | return NULL; |
| 127 | } |
| 128 | |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 129 | /* # raises appropriate IndexError if heap is empty */ |
| 130 | n = PyList_GET_SIZE(heap); |
| 131 | if (n == 0) { |
| 132 | PyErr_SetString(PyExc_IndexError, "index out of range"); |
| 133 | return NULL; |
| 134 | } |
| 135 | |
| 136 | lastelt = PyList_GET_ITEM(heap, n-1) ; |
| 137 | Py_INCREF(lastelt); |
| 138 | PyList_SetSlice(heap, n-1, n, NULL); |
| 139 | n--; |
| 140 | |
| 141 | if (!n) |
| 142 | return lastelt; |
| 143 | returnitem = PyList_GET_ITEM(heap, 0); |
| 144 | PyList_SET_ITEM(heap, 0, lastelt); |
| 145 | if (_siftup((PyListObject *)heap, 0) == -1) { |
| 146 | Py_DECREF(returnitem); |
| 147 | return NULL; |
| 148 | } |
| 149 | return returnitem; |
| 150 | } |
| 151 | |
| 152 | PyDoc_STRVAR(heappop_doc, |
| 153 | "Pop the smallest item off the heap, maintaining the heap invariant."); |
| 154 | |
Neal Norwitz | 9342fb4 | 2003-12-13 22:31:53 +0000 | [diff] [blame] | 155 | static PyObject * |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 156 | heapreplace(PyObject *self, PyObject *args) |
| 157 | { |
| 158 | PyObject *heap, *item, *returnitem; |
| 159 | |
| 160 | if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item)) |
| 161 | return NULL; |
| 162 | |
| 163 | if (!PyList_Check(heap)) { |
Raymond Hettinger | 6dab052 | 2003-11-15 12:40:28 +0000 | [diff] [blame] | 164 | PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 165 | return NULL; |
| 166 | } |
| 167 | |
| 168 | if (PyList_GET_SIZE(heap) < 1) { |
| 169 | PyErr_SetString(PyExc_IndexError, "index out of range"); |
| 170 | return NULL; |
| 171 | } |
| 172 | |
| 173 | returnitem = PyList_GET_ITEM(heap, 0); |
| 174 | Py_INCREF(item); |
| 175 | PyList_SET_ITEM(heap, 0, item); |
| 176 | if (_siftup((PyListObject *)heap, 0) == -1) { |
| 177 | Py_DECREF(returnitem); |
| 178 | return NULL; |
| 179 | } |
| 180 | return returnitem; |
| 181 | } |
| 182 | |
| 183 | PyDoc_STRVAR(heapreplace_doc, |
| 184 | "Pop and return the current smallest value, and add the new item.\n\ |
| 185 | \n\ |
| 186 | This is more efficient than heappop() followed by heappush(), and can be\n\ |
| 187 | more appropriate when using a fixed-size heap. Note that the value\n\ |
| 188 | returned may be larger than item! That constrains reasonable uses of\n\ |
| 189 | this routine.\n"); |
| 190 | |
Neal Norwitz | 9342fb4 | 2003-12-13 22:31:53 +0000 | [diff] [blame] | 191 | static PyObject * |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 192 | heapify(PyObject *self, PyObject *heap) |
| 193 | { |
| 194 | int i, n; |
| 195 | |
| 196 | if (!PyList_Check(heap)) { |
Raymond Hettinger | 6dab052 | 2003-11-15 12:40:28 +0000 | [diff] [blame] | 197 | PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); |
Raymond Hettinger | b3af181 | 2003-11-08 10:24:38 +0000 | [diff] [blame] | 198 | return NULL; |
| 199 | } |
| 200 | |
| 201 | n = PyList_GET_SIZE(heap); |
| 202 | /* Transform bottom-up. The largest index there's any point to |
| 203 | looking at is the largest with a child index in-range, so must |
| 204 | have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is |
| 205 | (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If |
| 206 | n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest, |
| 207 | and that's again n//2-1. |
| 208 | */ |
| 209 | for (i=n/2-1 ; i>=0 ; i--) |
| 210 | if(_siftup((PyListObject *)heap, i) == -1) |
| 211 | return NULL; |
| 212 | Py_INCREF(Py_None); |
| 213 | return Py_None; |
| 214 | } |
| 215 | |
| 216 | PyDoc_STRVAR(heapify_doc, |
| 217 | "Transform list into a heap, in-place, in O(len(heap)) time."); |
| 218 | |
| 219 | static PyMethodDef heapq_methods[] = { |
| 220 | {"heappush", (PyCFunction)heappush, |
| 221 | METH_VARARGS, heappush_doc}, |
| 222 | {"heappop", (PyCFunction)heappop, |
| 223 | METH_O, heappop_doc}, |
| 224 | {"heapreplace", (PyCFunction)heapreplace, |
| 225 | METH_VARARGS, heapreplace_doc}, |
| 226 | {"heapify", (PyCFunction)heapify, |
| 227 | METH_O, heapify_doc}, |
| 228 | {NULL, NULL} /* sentinel */ |
| 229 | }; |
| 230 | |
| 231 | PyDoc_STRVAR(module_doc, |
| 232 | "Heap queue algorithm (a.k.a. priority queue).\n\ |
| 233 | \n\ |
| 234 | Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\ |
| 235 | all k, counting elements from 0. For the sake of comparison,\n\ |
| 236 | non-existing elements are considered to be infinite. The interesting\n\ |
| 237 | property of a heap is that a[0] is always its smallest element.\n\ |
| 238 | \n\ |
| 239 | Usage:\n\ |
| 240 | \n\ |
| 241 | heap = [] # creates an empty heap\n\ |
| 242 | heappush(heap, item) # pushes a new item on the heap\n\ |
| 243 | item = heappop(heap) # pops the smallest item from the heap\n\ |
| 244 | item = heap[0] # smallest item on the heap without popping it\n\ |
| 245 | heapify(x) # transforms list into a heap, in-place, in linear time\n\ |
| 246 | item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\ |
| 247 | # new item; the heap size is unchanged\n\ |
| 248 | \n\ |
| 249 | Our API differs from textbook heap algorithms as follows:\n\ |
| 250 | \n\ |
| 251 | - We use 0-based indexing. This makes the relationship between the\n\ |
| 252 | index for a node and the indexes for its children slightly less\n\ |
| 253 | obvious, but is more suitable since Python uses 0-based indexing.\n\ |
| 254 | \n\ |
| 255 | - Our heappop() method returns the smallest item, not the largest.\n\ |
| 256 | \n\ |
| 257 | These two make it possible to view the heap as a regular Python list\n\ |
| 258 | without surprises: heap[0] is the smallest item, and heap.sort()\n\ |
| 259 | maintains the heap invariant!\n"); |
| 260 | |
| 261 | |
| 262 | PyDoc_STRVAR(__about__, |
| 263 | "Heap queues\n\ |
| 264 | \n\ |
| 265 | [explanation by François Pinard]\n\ |
| 266 | \n\ |
| 267 | Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\ |
| 268 | all k, counting elements from 0. For the sake of comparison,\n\ |
| 269 | non-existing elements are considered to be infinite. The interesting\n\ |
| 270 | property of a heap is that a[0] is always its smallest element.\n" |
| 271 | "\n\ |
| 272 | The strange invariant above is meant to be an efficient memory\n\ |
| 273 | representation for a tournament. The numbers below are `k', not a[k]:\n\ |
| 274 | \n\ |
| 275 | 0\n\ |
| 276 | \n\ |
| 277 | 1 2\n\ |
| 278 | \n\ |
| 279 | 3 4 5 6\n\ |
| 280 | \n\ |
| 281 | 7 8 9 10 11 12 13 14\n\ |
| 282 | \n\ |
| 283 | 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\ |
| 284 | \n\ |
| 285 | \n\ |
| 286 | In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\ |
| 287 | an usual binary tournament we see in sports, each cell is the winner\n\ |
| 288 | over the two cells it tops, and we can trace the winner down the tree\n\ |
| 289 | to see all opponents s/he had. However, in many computer applications\n\ |
| 290 | of such tournaments, we do not need to trace the history of a winner.\n\ |
| 291 | To be more memory efficient, when a winner is promoted, we try to\n\ |
| 292 | replace it by something else at a lower level, and the rule becomes\n\ |
| 293 | that a cell and the two cells it tops contain three different items,\n\ |
| 294 | but the top cell \"wins\" over the two topped cells.\n" |
| 295 | "\n\ |
| 296 | If this heap invariant is protected at all time, index 0 is clearly\n\ |
| 297 | the overall winner. The simplest algorithmic way to remove it and\n\ |
| 298 | find the \"next\" winner is to move some loser (let's say cell 30 in the\n\ |
| 299 | diagram above) into the 0 position, and then percolate this new 0 down\n\ |
| 300 | the tree, exchanging values, until the invariant is re-established.\n\ |
| 301 | This is clearly logarithmic on the total number of items in the tree.\n\ |
| 302 | By iterating over all items, you get an O(n ln n) sort.\n" |
| 303 | "\n\ |
| 304 | A nice feature of this sort is that you can efficiently insert new\n\ |
| 305 | items while the sort is going on, provided that the inserted items are\n\ |
| 306 | not \"better\" than the last 0'th element you extracted. This is\n\ |
| 307 | especially useful in simulation contexts, where the tree holds all\n\ |
| 308 | incoming events, and the \"win\" condition means the smallest scheduled\n\ |
| 309 | time. When an event schedule other events for execution, they are\n\ |
| 310 | scheduled into the future, so they can easily go into the heap. So, a\n\ |
| 311 | heap is a good structure for implementing schedulers (this is what I\n\ |
| 312 | used for my MIDI sequencer :-).\n" |
| 313 | "\n\ |
| 314 | Various structures for implementing schedulers have been extensively\n\ |
| 315 | studied, and heaps are good for this, as they are reasonably speedy,\n\ |
| 316 | the speed is almost constant, and the worst case is not much different\n\ |
| 317 | than the average case. However, there are other representations which\n\ |
| 318 | are more efficient overall, yet the worst cases might be terrible.\n" |
| 319 | "\n\ |
| 320 | Heaps are also very useful in big disk sorts. You most probably all\n\ |
| 321 | know that a big sort implies producing \"runs\" (which are pre-sorted\n\ |
| 322 | sequences, which size is usually related to the amount of CPU memory),\n\ |
| 323 | followed by a merging passes for these runs, which merging is often\n\ |
| 324 | very cleverly organised[1]. It is very important that the initial\n\ |
| 325 | sort produces the longest runs possible. Tournaments are a good way\n\ |
| 326 | to that. If, using all the memory available to hold a tournament, you\n\ |
| 327 | replace and percolate items that happen to fit the current run, you'll\n\ |
| 328 | produce runs which are twice the size of the memory for random input,\n\ |
| 329 | and much better for input fuzzily ordered.\n" |
| 330 | "\n\ |
| 331 | Moreover, if you output the 0'th item on disk and get an input which\n\ |
| 332 | may not fit in the current tournament (because the value \"wins\" over\n\ |
| 333 | the last output value), it cannot fit in the heap, so the size of the\n\ |
| 334 | heap decreases. The freed memory could be cleverly reused immediately\n\ |
| 335 | for progressively building a second heap, which grows at exactly the\n\ |
| 336 | same rate the first heap is melting. When the first heap completely\n\ |
| 337 | vanishes, you switch heaps and start a new run. Clever and quite\n\ |
| 338 | effective!\n\ |
| 339 | \n\ |
| 340 | In a word, heaps are useful memory structures to know. I use them in\n\ |
| 341 | a few applications, and I think it is good to keep a `heap' module\n\ |
| 342 | around. :-)\n" |
| 343 | "\n\ |
| 344 | --------------------\n\ |
| 345 | [1] The disk balancing algorithms which are current, nowadays, are\n\ |
| 346 | more annoying than clever, and this is a consequence of the seeking\n\ |
| 347 | capabilities of the disks. On devices which cannot seek, like big\n\ |
| 348 | tape drives, the story was quite different, and one had to be very\n\ |
| 349 | clever to ensure (far in advance) that each tape movement will be the\n\ |
| 350 | most effective possible (that is, will best participate at\n\ |
| 351 | \"progressing\" the merge). Some tapes were even able to read\n\ |
| 352 | backwards, and this was also used to avoid the rewinding time.\n\ |
| 353 | Believe me, real good tape sorts were quite spectacular to watch!\n\ |
| 354 | From all times, sorting has always been a Great Art! :-)\n"); |
| 355 | |
| 356 | PyMODINIT_FUNC |
| 357 | initheapq(void) |
| 358 | { |
| 359 | PyObject *m; |
| 360 | |
| 361 | m = Py_InitModule3("heapq", heapq_methods, module_doc); |
| 362 | PyModule_AddObject(m, "__about__", PyString_FromString(__about__)); |
| 363 | } |
| 364 | |