_heapqmodule.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. /* Drop in replacement for heapq.py
  2. C implementation derived directly from heapq.py in Py2.3
  3. which was written by Kevin O'Connor, augmented by Tim Peters,
  4. annotated by François Pinard, and converted to C by Raymond Hettinger.
  5. */
  6. #ifndef Py_BUILD_CORE_BUILTIN
  7. # define Py_BUILD_CORE_MODULE 1
  8. #endif
  9. #include "Python.h"
  10. #include "pycore_list.h" // _PyList_ITEMS()
  11. #include "clinic/_heapqmodule.c.h"
  12. /*[clinic input]
  13. module _heapq
  14. [clinic start generated code]*/
  15. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=d7cca0a2e4c0ceb3]*/
  16. static int
  17. siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
  18. {
  19. PyObject *newitem, *parent, **arr;
  20. Py_ssize_t parentpos, size;
  21. int cmp;
  22. assert(PyList_Check(heap));
  23. size = PyList_GET_SIZE(heap);
  24. if (pos >= size) {
  25. PyErr_SetString(PyExc_IndexError, "index out of range");
  26. return -1;
  27. }
  28. /* Follow the path to the root, moving parents down until finding
  29. a place newitem fits. */
  30. arr = _PyList_ITEMS(heap);
  31. newitem = arr[pos];
  32. while (pos > startpos) {
  33. parentpos = (pos - 1) >> 1;
  34. parent = arr[parentpos];
  35. Py_INCREF(newitem);
  36. Py_INCREF(parent);
  37. cmp = PyObject_RichCompareBool(newitem, parent, Py_LT);
  38. Py_DECREF(parent);
  39. Py_DECREF(newitem);
  40. if (cmp < 0)
  41. return -1;
  42. if (size != PyList_GET_SIZE(heap)) {
  43. PyErr_SetString(PyExc_RuntimeError,
  44. "list changed size during iteration");
  45. return -1;
  46. }
  47. if (cmp == 0)
  48. break;
  49. arr = _PyList_ITEMS(heap);
  50. parent = arr[parentpos];
  51. newitem = arr[pos];
  52. arr[parentpos] = newitem;
  53. arr[pos] = parent;
  54. pos = parentpos;
  55. }
  56. return 0;
  57. }
  58. static int
  59. siftup(PyListObject *heap, Py_ssize_t pos)
  60. {
  61. Py_ssize_t startpos, endpos, childpos, limit;
  62. PyObject *tmp1, *tmp2, **arr;
  63. int cmp;
  64. assert(PyList_Check(heap));
  65. endpos = PyList_GET_SIZE(heap);
  66. startpos = pos;
  67. if (pos >= endpos) {
  68. PyErr_SetString(PyExc_IndexError, "index out of range");
  69. return -1;
  70. }
  71. /* Bubble up the smaller child until hitting a leaf. */
  72. arr = _PyList_ITEMS(heap);
  73. limit = endpos >> 1; /* smallest pos that has no child */
  74. while (pos < limit) {
  75. /* Set childpos to index of smaller child. */
  76. childpos = 2*pos + 1; /* leftmost child position */
  77. if (childpos + 1 < endpos) {
  78. PyObject* a = arr[childpos];
  79. PyObject* b = arr[childpos + 1];
  80. Py_INCREF(a);
  81. Py_INCREF(b);
  82. cmp = PyObject_RichCompareBool(a, b, Py_LT);
  83. Py_DECREF(a);
  84. Py_DECREF(b);
  85. if (cmp < 0)
  86. return -1;
  87. childpos += ((unsigned)cmp ^ 1); /* increment when cmp==0 */
  88. arr = _PyList_ITEMS(heap); /* arr may have changed */
  89. if (endpos != PyList_GET_SIZE(heap)) {
  90. PyErr_SetString(PyExc_RuntimeError,
  91. "list changed size during iteration");
  92. return -1;
  93. }
  94. }
  95. /* Move the smaller child up. */
  96. tmp1 = arr[childpos];
  97. tmp2 = arr[pos];
  98. arr[childpos] = tmp2;
  99. arr[pos] = tmp1;
  100. pos = childpos;
  101. }
  102. /* Bubble it up to its final resting place (by sifting its parents down). */
  103. return siftdown(heap, startpos, pos);
  104. }
  105. /*[clinic input]
  106. _heapq.heappush
  107. heap: object(subclass_of='&PyList_Type')
  108. item: object
  109. /
  110. Push item onto heap, maintaining the heap invariant.
  111. [clinic start generated code]*/
  112. static PyObject *
  113. _heapq_heappush_impl(PyObject *module, PyObject *heap, PyObject *item)
  114. /*[clinic end generated code: output=912c094f47663935 input=7c69611f3698aceb]*/
  115. {
  116. if (PyList_Append(heap, item))
  117. return NULL;
  118. if (siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1))
  119. return NULL;
  120. Py_RETURN_NONE;
  121. }
  122. static PyObject *
  123. heappop_internal(PyObject *heap, int siftup_func(PyListObject *, Py_ssize_t))
  124. {
  125. PyObject *lastelt, *returnitem;
  126. Py_ssize_t n;
  127. /* raises IndexError if the heap is empty */
  128. n = PyList_GET_SIZE(heap);
  129. if (n == 0) {
  130. PyErr_SetString(PyExc_IndexError, "index out of range");
  131. return NULL;
  132. }
  133. lastelt = PyList_GET_ITEM(heap, n-1) ;
  134. Py_INCREF(lastelt);
  135. if (PyList_SetSlice(heap, n-1, n, NULL)) {
  136. Py_DECREF(lastelt);
  137. return NULL;
  138. }
  139. n--;
  140. if (!n)
  141. return lastelt;
  142. returnitem = PyList_GET_ITEM(heap, 0);
  143. PyList_SET_ITEM(heap, 0, lastelt);
  144. if (siftup_func((PyListObject *)heap, 0)) {
  145. Py_DECREF(returnitem);
  146. return NULL;
  147. }
  148. return returnitem;
  149. }
  150. /*[clinic input]
  151. _heapq.heappop
  152. heap: object(subclass_of='&PyList_Type')
  153. /
  154. Pop the smallest item off the heap, maintaining the heap invariant.
  155. [clinic start generated code]*/
  156. static PyObject *
  157. _heapq_heappop_impl(PyObject *module, PyObject *heap)
  158. /*[clinic end generated code: output=96dfe82d37d9af76 input=91487987a583c856]*/
  159. {
  160. return heappop_internal(heap, siftup);
  161. }
  162. static PyObject *
  163. heapreplace_internal(PyObject *heap, PyObject *item, int siftup_func(PyListObject *, Py_ssize_t))
  164. {
  165. PyObject *returnitem;
  166. if (PyList_GET_SIZE(heap) == 0) {
  167. PyErr_SetString(PyExc_IndexError, "index out of range");
  168. return NULL;
  169. }
  170. returnitem = PyList_GET_ITEM(heap, 0);
  171. PyList_SET_ITEM(heap, 0, Py_NewRef(item));
  172. if (siftup_func((PyListObject *)heap, 0)) {
  173. Py_DECREF(returnitem);
  174. return NULL;
  175. }
  176. return returnitem;
  177. }
  178. /*[clinic input]
  179. _heapq.heapreplace
  180. heap: object(subclass_of='&PyList_Type')
  181. item: object
  182. /
  183. Pop and return the current smallest value, and add the new item.
  184. This is more efficient than heappop() followed by heappush(), and can be
  185. more appropriate when using a fixed-size heap. Note that the value
  186. returned may be larger than item! That constrains reasonable uses of
  187. this routine unless written as part of a conditional replacement:
  188. if item > heap[0]:
  189. item = heapreplace(heap, item)
  190. [clinic start generated code]*/
  191. static PyObject *
  192. _heapq_heapreplace_impl(PyObject *module, PyObject *heap, PyObject *item)
  193. /*[clinic end generated code: output=82ea55be8fbe24b4 input=719202ac02ba10c8]*/
  194. {
  195. return heapreplace_internal(heap, item, siftup);
  196. }
  197. /*[clinic input]
  198. _heapq.heappushpop
  199. heap: object(subclass_of='&PyList_Type')
  200. item: object
  201. /
  202. Push item on the heap, then pop and return the smallest item from the heap.
  203. The combined action runs more efficiently than heappush() followed by
  204. a separate call to heappop().
  205. [clinic start generated code]*/
  206. static PyObject *
  207. _heapq_heappushpop_impl(PyObject *module, PyObject *heap, PyObject *item)
  208. /*[clinic end generated code: output=67231dc98ed5774f input=5dc701f1eb4a4aa7]*/
  209. {
  210. PyObject *returnitem;
  211. int cmp;
  212. if (PyList_GET_SIZE(heap) == 0) {
  213. return Py_NewRef(item);
  214. }
  215. PyObject* top = PyList_GET_ITEM(heap, 0);
  216. Py_INCREF(top);
  217. cmp = PyObject_RichCompareBool(top, item, Py_LT);
  218. Py_DECREF(top);
  219. if (cmp < 0)
  220. return NULL;
  221. if (cmp == 0) {
  222. return Py_NewRef(item);
  223. }
  224. if (PyList_GET_SIZE(heap) == 0) {
  225. PyErr_SetString(PyExc_IndexError, "index out of range");
  226. return NULL;
  227. }
  228. returnitem = PyList_GET_ITEM(heap, 0);
  229. PyList_SET_ITEM(heap, 0, Py_NewRef(item));
  230. if (siftup((PyListObject *)heap, 0)) {
  231. Py_DECREF(returnitem);
  232. return NULL;
  233. }
  234. return returnitem;
  235. }
  236. static Py_ssize_t
  237. keep_top_bit(Py_ssize_t n)
  238. {
  239. int i = 0;
  240. while (n > 1) {
  241. n >>= 1;
  242. i++;
  243. }
  244. return n << i;
  245. }
  246. /* Cache friendly version of heapify()
  247. -----------------------------------
  248. Build-up a heap in O(n) time by performing siftup() operations
  249. on nodes whose children are already heaps.
  250. The simplest way is to sift the nodes in reverse order from
  251. n//2-1 to 0 inclusive. The downside is that children may be
  252. out of cache by the time their parent is reached.
  253. A better way is to not wait for the children to go out of cache.
  254. Once a sibling pair of child nodes have been sifted, immediately
  255. sift their parent node (while the children are still in cache).
  256. Both ways build child heaps before their parents, so both ways
  257. do the exact same number of comparisons and produce exactly
  258. the same heap. The only difference is that the traversal
  259. order is optimized for cache efficiency.
  260. */
  261. static PyObject *
  262. cache_friendly_heapify(PyObject *heap, int siftup_func(PyListObject *, Py_ssize_t))
  263. {
  264. Py_ssize_t i, j, m, mhalf, leftmost;
  265. m = PyList_GET_SIZE(heap) >> 1; /* index of first childless node */
  266. leftmost = keep_top_bit(m + 1) - 1; /* leftmost node in row of m */
  267. mhalf = m >> 1; /* parent of first childless node */
  268. for (i = leftmost - 1 ; i >= mhalf ; i--) {
  269. j = i;
  270. while (1) {
  271. if (siftup_func((PyListObject *)heap, j))
  272. return NULL;
  273. if (!(j & 1))
  274. break;
  275. j >>= 1;
  276. }
  277. }
  278. for (i = m - 1 ; i >= leftmost ; i--) {
  279. j = i;
  280. while (1) {
  281. if (siftup_func((PyListObject *)heap, j))
  282. return NULL;
  283. if (!(j & 1))
  284. break;
  285. j >>= 1;
  286. }
  287. }
  288. Py_RETURN_NONE;
  289. }
  290. static PyObject *
  291. heapify_internal(PyObject *heap, int siftup_func(PyListObject *, Py_ssize_t))
  292. {
  293. Py_ssize_t i, n;
  294. /* For heaps likely to be bigger than L1 cache, we use the cache
  295. friendly heapify function. For smaller heaps that fit entirely
  296. in cache, we prefer the simpler algorithm with less branching.
  297. */
  298. n = PyList_GET_SIZE(heap);
  299. if (n > 2500)
  300. return cache_friendly_heapify(heap, siftup_func);
  301. /* Transform bottom-up. The largest index there's any point to
  302. looking at is the largest with a child index in-range, so must
  303. have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
  304. (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
  305. n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
  306. and that's again n//2-1.
  307. */
  308. for (i = (n >> 1) - 1 ; i >= 0 ; i--)
  309. if (siftup_func((PyListObject *)heap, i))
  310. return NULL;
  311. Py_RETURN_NONE;
  312. }
  313. /*[clinic input]
  314. _heapq.heapify
  315. heap: object(subclass_of='&PyList_Type')
  316. /
  317. Transform list into a heap, in-place, in O(len(heap)) time.
  318. [clinic start generated code]*/
  319. static PyObject *
  320. _heapq_heapify_impl(PyObject *module, PyObject *heap)
  321. /*[clinic end generated code: output=e63a636fcf83d6d0 input=53bb7a2166febb73]*/
  322. {
  323. return heapify_internal(heap, siftup);
  324. }
  325. static int
  326. siftdown_max(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
  327. {
  328. PyObject *newitem, *parent, **arr;
  329. Py_ssize_t parentpos, size;
  330. int cmp;
  331. assert(PyList_Check(heap));
  332. size = PyList_GET_SIZE(heap);
  333. if (pos >= size) {
  334. PyErr_SetString(PyExc_IndexError, "index out of range");
  335. return -1;
  336. }
  337. /* Follow the path to the root, moving parents down until finding
  338. a place newitem fits. */
  339. arr = _PyList_ITEMS(heap);
  340. newitem = arr[pos];
  341. while (pos > startpos) {
  342. parentpos = (pos - 1) >> 1;
  343. parent = Py_NewRef(arr[parentpos]);
  344. Py_INCREF(newitem);
  345. cmp = PyObject_RichCompareBool(parent, newitem, Py_LT);
  346. Py_DECREF(parent);
  347. Py_DECREF(newitem);
  348. if (cmp < 0)
  349. return -1;
  350. if (size != PyList_GET_SIZE(heap)) {
  351. PyErr_SetString(PyExc_RuntimeError,
  352. "list changed size during iteration");
  353. return -1;
  354. }
  355. if (cmp == 0)
  356. break;
  357. arr = _PyList_ITEMS(heap);
  358. parent = arr[parentpos];
  359. newitem = arr[pos];
  360. arr[parentpos] = newitem;
  361. arr[pos] = parent;
  362. pos = parentpos;
  363. }
  364. return 0;
  365. }
  366. static int
  367. siftup_max(PyListObject *heap, Py_ssize_t pos)
  368. {
  369. Py_ssize_t startpos, endpos, childpos, limit;
  370. PyObject *tmp1, *tmp2, **arr;
  371. int cmp;
  372. assert(PyList_Check(heap));
  373. endpos = PyList_GET_SIZE(heap);
  374. startpos = pos;
  375. if (pos >= endpos) {
  376. PyErr_SetString(PyExc_IndexError, "index out of range");
  377. return -1;
  378. }
  379. /* Bubble up the smaller child until hitting a leaf. */
  380. arr = _PyList_ITEMS(heap);
  381. limit = endpos >> 1; /* smallest pos that has no child */
  382. while (pos < limit) {
  383. /* Set childpos to index of smaller child. */
  384. childpos = 2*pos + 1; /* leftmost child position */
  385. if (childpos + 1 < endpos) {
  386. PyObject* a = arr[childpos + 1];
  387. PyObject* b = arr[childpos];
  388. Py_INCREF(a);
  389. Py_INCREF(b);
  390. cmp = PyObject_RichCompareBool(a, b, Py_LT);
  391. Py_DECREF(a);
  392. Py_DECREF(b);
  393. if (cmp < 0)
  394. return -1;
  395. childpos += ((unsigned)cmp ^ 1); /* increment when cmp==0 */
  396. arr = _PyList_ITEMS(heap); /* arr may have changed */
  397. if (endpos != PyList_GET_SIZE(heap)) {
  398. PyErr_SetString(PyExc_RuntimeError,
  399. "list changed size during iteration");
  400. return -1;
  401. }
  402. }
  403. /* Move the smaller child up. */
  404. tmp1 = arr[childpos];
  405. tmp2 = arr[pos];
  406. arr[childpos] = tmp2;
  407. arr[pos] = tmp1;
  408. pos = childpos;
  409. }
  410. /* Bubble it up to its final resting place (by sifting its parents down). */
  411. return siftdown_max(heap, startpos, pos);
  412. }
  413. /*[clinic input]
  414. _heapq._heappop_max
  415. heap: object(subclass_of='&PyList_Type')
  416. /
  417. Maxheap variant of heappop.
  418. [clinic start generated code]*/
  419. static PyObject *
  420. _heapq__heappop_max_impl(PyObject *module, PyObject *heap)
  421. /*[clinic end generated code: output=9e77aadd4e6a8760 input=362c06e1c7484793]*/
  422. {
  423. return heappop_internal(heap, siftup_max);
  424. }
  425. /*[clinic input]
  426. _heapq._heapreplace_max
  427. heap: object(subclass_of='&PyList_Type')
  428. item: object
  429. /
  430. Maxheap variant of heapreplace.
  431. [clinic start generated code]*/
  432. static PyObject *
  433. _heapq__heapreplace_max_impl(PyObject *module, PyObject *heap,
  434. PyObject *item)
  435. /*[clinic end generated code: output=8ad7545e4a5e8adb input=f2dd27cbadb948d7]*/
  436. {
  437. return heapreplace_internal(heap, item, siftup_max);
  438. }
  439. /*[clinic input]
  440. _heapq._heapify_max
  441. heap: object(subclass_of='&PyList_Type')
  442. /
  443. Maxheap variant of heapify.
  444. [clinic start generated code]*/
  445. static PyObject *
  446. _heapq__heapify_max_impl(PyObject *module, PyObject *heap)
  447. /*[clinic end generated code: output=2cb028beb4a8b65e input=c1f765ee69f124b8]*/
  448. {
  449. return heapify_internal(heap, siftup_max);
  450. }
  451. static PyMethodDef heapq_methods[] = {
  452. _HEAPQ_HEAPPUSH_METHODDEF
  453. _HEAPQ_HEAPPUSHPOP_METHODDEF
  454. _HEAPQ_HEAPPOP_METHODDEF
  455. _HEAPQ_HEAPREPLACE_METHODDEF
  456. _HEAPQ_HEAPIFY_METHODDEF
  457. _HEAPQ__HEAPPOP_MAX_METHODDEF
  458. _HEAPQ__HEAPIFY_MAX_METHODDEF
  459. _HEAPQ__HEAPREPLACE_MAX_METHODDEF
  460. {NULL, NULL} /* sentinel */
  461. };
  462. PyDoc_STRVAR(module_doc,
  463. "Heap queue algorithm (a.k.a. priority queue).\n\
  464. \n\
  465. Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
  466. all k, counting elements from 0. For the sake of comparison,\n\
  467. non-existing elements are considered to be infinite. The interesting\n\
  468. property of a heap is that a[0] is always its smallest element.\n\
  469. \n\
  470. Usage:\n\
  471. \n\
  472. heap = [] # creates an empty heap\n\
  473. heappush(heap, item) # pushes a new item on the heap\n\
  474. item = heappop(heap) # pops the smallest item from the heap\n\
  475. item = heap[0] # smallest item on the heap without popping it\n\
  476. heapify(x) # transforms list into a heap, in-place, in linear time\n\
  477. item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
  478. # new item; the heap size is unchanged\n\
  479. \n\
  480. Our API differs from textbook heap algorithms as follows:\n\
  481. \n\
  482. - We use 0-based indexing. This makes the relationship between the\n\
  483. index for a node and the indexes for its children slightly less\n\
  484. obvious, but is more suitable since Python uses 0-based indexing.\n\
  485. \n\
  486. - Our heappop() method returns the smallest item, not the largest.\n\
  487. \n\
  488. These two make it possible to view the heap as a regular Python list\n\
  489. without surprises: heap[0] is the smallest item, and heap.sort()\n\
  490. maintains the heap invariant!\n");
  491. PyDoc_STRVAR(__about__,
  492. "Heap queues\n\
  493. \n\
  494. [explanation by Fran\xc3\xa7ois Pinard]\n\
  495. \n\
  496. Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
  497. all k, counting elements from 0. For the sake of comparison,\n\
  498. non-existing elements are considered to be infinite. The interesting\n\
  499. property of a heap is that a[0] is always its smallest element.\n"
  500. "\n\
  501. The strange invariant above is meant to be an efficient memory\n\
  502. representation for a tournament. The numbers below are `k', not a[k]:\n\
  503. \n\
  504. 0\n\
  505. \n\
  506. 1 2\n\
  507. \n\
  508. 3 4 5 6\n\
  509. \n\
  510. 7 8 9 10 11 12 13 14\n\
  511. \n\
  512. 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
  513. \n\
  514. \n\
  515. In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
  516. a usual binary tournament we see in sports, each cell is the winner\n\
  517. over the two cells it tops, and we can trace the winner down the tree\n\
  518. to see all opponents s/he had. However, in many computer applications\n\
  519. of such tournaments, we do not need to trace the history of a winner.\n\
  520. To be more memory efficient, when a winner is promoted, we try to\n\
  521. replace it by something else at a lower level, and the rule becomes\n\
  522. that a cell and the two cells it tops contain three different items,\n\
  523. but the top cell \"wins\" over the two topped cells.\n"
  524. "\n\
  525. If this heap invariant is protected at all time, index 0 is clearly\n\
  526. the overall winner. The simplest algorithmic way to remove it and\n\
  527. find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
  528. diagram above) into the 0 position, and then percolate this new 0 down\n\
  529. the tree, exchanging values, until the invariant is re-established.\n\
  530. This is clearly logarithmic on the total number of items in the tree.\n\
  531. By iterating over all items, you get an O(n ln n) sort.\n"
  532. "\n\
  533. A nice feature of this sort is that you can efficiently insert new\n\
  534. items while the sort is going on, provided that the inserted items are\n\
  535. not \"better\" than the last 0'th element you extracted. This is\n\
  536. especially useful in simulation contexts, where the tree holds all\n\
  537. incoming events, and the \"win\" condition means the smallest scheduled\n\
  538. time. When an event schedule other events for execution, they are\n\
  539. scheduled into the future, so they can easily go into the heap. So, a\n\
  540. heap is a good structure for implementing schedulers (this is what I\n\
  541. used for my MIDI sequencer :-).\n"
  542. "\n\
  543. Various structures for implementing schedulers have been extensively\n\
  544. studied, and heaps are good for this, as they are reasonably speedy,\n\
  545. the speed is almost constant, and the worst case is not much different\n\
  546. than the average case. However, there are other representations which\n\
  547. are more efficient overall, yet the worst cases might be terrible.\n"
  548. "\n\
  549. Heaps are also very useful in big disk sorts. You most probably all\n\
  550. know that a big sort implies producing \"runs\" (which are pre-sorted\n\
  551. sequences, which size is usually related to the amount of CPU memory),\n\
  552. followed by a merging passes for these runs, which merging is often\n\
  553. very cleverly organised[1]. It is very important that the initial\n\
  554. sort produces the longest runs possible. Tournaments are a good way\n\
  555. to that. If, using all the memory available to hold a tournament, you\n\
  556. replace and percolate items that happen to fit the current run, you'll\n\
  557. produce runs which are twice the size of the memory for random input,\n\
  558. and much better for input fuzzily ordered.\n"
  559. "\n\
  560. Moreover, if you output the 0'th item on disk and get an input which\n\
  561. may not fit in the current tournament (because the value \"wins\" over\n\
  562. the last output value), it cannot fit in the heap, so the size of the\n\
  563. heap decreases. The freed memory could be cleverly reused immediately\n\
  564. for progressively building a second heap, which grows at exactly the\n\
  565. same rate the first heap is melting. When the first heap completely\n\
  566. vanishes, you switch heaps and start a new run. Clever and quite\n\
  567. effective!\n\
  568. \n\
  569. In a word, heaps are useful memory structures to know. I use them in\n\
  570. a few applications, and I think it is good to keep a `heap' module\n\
  571. around. :-)\n"
  572. "\n\
  573. --------------------\n\
  574. [1] The disk balancing algorithms which are current, nowadays, are\n\
  575. more annoying than clever, and this is a consequence of the seeking\n\
  576. capabilities of the disks. On devices which cannot seek, like big\n\
  577. tape drives, the story was quite different, and one had to be very\n\
  578. clever to ensure (far in advance) that each tape movement will be the\n\
  579. most effective possible (that is, will best participate at\n\
  580. \"progressing\" the merge). Some tapes were even able to read\n\
  581. backwards, and this was also used to avoid the rewinding time.\n\
  582. Believe me, real good tape sorts were quite spectacular to watch!\n\
  583. From all times, sorting has always been a Great Art! :-)\n");
  584. static int
  585. heapq_exec(PyObject *m)
  586. {
  587. PyObject *about = PyUnicode_FromString(__about__);
  588. if (PyModule_AddObject(m, "__about__", about) < 0) {
  589. Py_DECREF(about);
  590. return -1;
  591. }
  592. return 0;
  593. }
  594. static struct PyModuleDef_Slot heapq_slots[] = {
  595. {Py_mod_exec, heapq_exec},
  596. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  597. {0, NULL}
  598. };
  599. static struct PyModuleDef _heapqmodule = {
  600. PyModuleDef_HEAD_INIT,
  601. "_heapq",
  602. module_doc,
  603. 0,
  604. heapq_methods,
  605. heapq_slots,
  606. NULL,
  607. NULL,
  608. NULL
  609. };
  610. PyMODINIT_FUNC
  611. PyInit__heapq(void)
  612. {
  613. return PyModuleDef_Init(&_heapqmodule);
  614. }