grthtrhthjhtyjytjytkergtrhtrjytjerhrfh4:24 29/09/2026ó ö6w1üt�ãóZ•SrSr/SQrSrSrSrSrSrSrS r S r S r S r S r SrSSS.SjrSSjrSSjrSSK7 SSKJ r SSKJ r SSKJr \S:XaSSKr\"\R."55 gg!\a N@f=f!\a NEf=f!\a NJf=f!\a NOf=f)a‚Heap queue algorithm (a.k.a. priority queue). Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that a[0] is always its smallest element. Usage: heap = [] # creates an empty heap heappush(heap, item) # pushes a new item on the heap item = heappop(heap) # pops the smallest item from the heap item = heap[0] # smallest item on the heap without popping it heapify(x) # transforms list into a heap, in-place, in linear time item = heappushpop(heap, item) # pushes a new item and then returns # the smallest item; the heap size is unchanged item = heapreplace(heap, item) # pops and returns smallest item, and adds # new item; the heap size is unchanged Our API differs from textbook heap algorithms as follows: - We use 0-based indexing. This makes the relationship between the index for a node and the indexes for its children slightly less obvious, but is more suitable since Python uses 0-based indexing. - Our heappop() method returns the smallest item, not the largest. These two make it possible to view the heap as a regular Python list without surprises: heap[0] is the smallest item, and heap.sort() maintains the heap invariant! uoHeap queues [explanation by François Pinard] Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that a[0] is always its smallest element. The strange invariant above is meant to be an efficient memory representation for a tournament. The numbers below are `k', not a[k]: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In a usual binary tournament we see in sports, each cell is the winner over the two cells it tops, and we can trace the winner down the tree to see all opponents s/he had. However, in many computer applications of such tournaments, we do not need to trace the history of a winner. To be more memory efficient, when a winner is promoted, we try to replace it by something else at a lower level, and the rule becomes that a cell and the two cells it tops contain three different items, but the top cell "wins" over the two topped cells. If this heap invariant is protected at all time, index 0 is clearly the overall winner. The simplest algorithmic way to remove it and find the "next" winner is to move some loser (let's say cell 30 in the diagram above) into the 0 position, and then percolate this new 0 down the tree, exchanging values, until the invariant is re-established. This is clearly logarithmic on the total number of items in the tree. By iterating over all items, you get an O(n ln n) sort. A nice feature of this sort is that you can efficiently insert new items while the sort is going on, provided that the inserted items are not "better" than the last 0'th element you extracted. This is especially useful in simulation contexts, where the tree holds all incoming events, and the "win" condition means the smallest scheduled time. When an event schedule other events for execution, they are scheduled into the future, so they can easily go into the heap. So, a heap is a good structure for implementing schedulers (this is what I used for my MIDI sequencer :-). Various structures for implementing schedulers have been extensively studied, and heaps are good for this, as they are reasonably speedy, the speed is almost constant, and the worst case is not much different than the average case. However, there are other representations which are more efficient overall, yet the worst cases might be terrible. Heaps are also very useful in big disk sorts. You most probably all know that a big sort implies producing "runs" (which are pre-sorted sequences, which size is usually related to the amount of CPU memory), followed by a merging passes for these runs, which merging is often very cleverly organised[1]. It is very important that the initial sort produces the longest runs possible. Tournaments are a good way to that. If, using all the memory available to hold a tournament, you replace and percolate items that happen to fit the current run, you'll produce runs which are twice the size of the memory for random input, and much better for input fuzzily ordered. Moreover, if you output the 0'th item on disk and get an input which may not fit in the current tournament (because the value "wins" over the last output value), it cannot fit in the heap, so the size of the heap decreases. The freed memory could be cleverly reused immediately for progressively building a second heap, which grows at exactly the same rate the first heap is melting. When the first heap completely vanishes, you switch heaps and start a new run. Clever and quite effective! In a word, heaps are useful memory structures to know. I use them in a few applications, and I think it is good to keep a `heap' module around. :-) -------------------- [1] The disk balancing algorithms which are current, nowadays, are more annoying than clever, and this is a consequence of the seeking capabilities of the disks. On devices which cannot seek, like big tape drives, the story was quite different, and one had to be very clever to ensure (far in advance) that each tape movement will be the most effective possible (that is, will best participate at "progressing" the merge). Some tapes were even able to read backwards, and this was also used to avoid the rewinding time. Believe me, real good tape sorts were quite spectacular to watch! From all times, sorting has always been a Great Art! :-) )ÚheappushÚheappopÚheapifyÚ heapreplaceÚmergeÚnlargestÚ nsmallestÚ heappushpopcóX•URU5 [US[U5S- 5 g)z4Push item onto heap, maintaining the heap invariant.ééN)ÚappendÚ _siftdownÚlen©ÚheapÚitems Ú,/opt/alt/python313/lib64/python3.13/heapq.pyrr„s"€à‡K�K�ÔÜ ˆd�A”s˜4“y ‘{Õ#ócób•UR5nU(aUSnXS'[US5 U$U$)zCPop the smallest item off the heap, maintaining the heap invariant.r )ÚpopÚ_siftup©rÚlasteltÚ returnitems rrr‰s5€à�h‰h‹j€GÞ Ø˜!‘Wˆ ؈Q‰Ü��aÔØÐØ €Nrcó0•USnXS'[US5 U$)a–Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable uses of this routine unless written as part of a conditional replacement: if item > heap[0]: item = heapreplace(heap, item) r ©r©rrrs rrr“s$€ð�a‘€J؈�GÜ ˆD�!ÔØ ÐrcóR•U(aUSU:aUSUsoS'[US5 U$)z1Fast version of a heappush followed by a heappop.r rrs rr r £s/€æ ��Q‘˜$“ؘQ™ ˆ ˆ�1‰gÜ��aÔØ €Krcól•[U5n[[US-55Hn[X5 M g)z8Transform list into a heap, in-place, in O(len(x)) time.éN)rÚreversedÚranger©ÚxÚnÚis rrrªs+€ä ˆA‹€Aô ”e˜A˜q™D“kÖ "ˆÜ�Ž ò#rcób•UR5nU(aUSnXS'[US5 U$U$)zMaxheap version of a heappop.r )rÚ _siftup_maxrs rÚ _heappop_maxr)µs5€à�h‰h‹j€GÞ Ø˜!‘Wˆ ؈Q‰Ü�D˜!ÔØÐØ €Nrcó0•USnXS'[US5 U$)z4Maxheap version of a heappop followed by a heappush.r )r(rs rÚ_heapreplace_maxr+¿s"€à�a‘€J؈�GÜ��aÔØ Ðrcól•[U5n[[US-55Hn[X5 M g)z;Transform list into a maxheap, in-place, in O(len(x)) time.r N)rr!r"r(r#s rÚ _heapify_maxr-Æs*€ä ˆA‹€AÜ ”e˜A˜q™D“kÖ "ˆÜ�AÖò#rcóR•XnX!:”aUS- S- nXnX5:aXPU'UnMX0U'g)Nr ©©rÚstartposÚposÚnewitemÚ parentposÚparents rrrÏsC€Ø‰i€Gð ‹.ؘ1‘W ‘Nˆ Ø‘ˆØ Ó Ø�‰I؈CÙ Ø Øˆ‚Ircóº•[U5nUnXnSU-S-nXR:a-US-nXb:a XX:dUnXX'UnSU-S-nXR:aM-X@U'[XU5 g)Nr r )rr©rr2Úendposr1r3ÚchildposÚrightposs rrrs€Ü �‹Y€FØ€H؉i€Gà�‰u�q‰y€HØ Ó à˜a‘<ˆØ Ó  T¡^°d±nÓ%D؈Hà‘Nˆ‰ ؈Ø�S‘5˜1‘9ˆð Õ ðˆ�IÜ ˆd˜cÕ"rcóR•XnX!:”aUS- S- nXnXS:aXPU'UnMX0U'g)zMaxheap variant of _siftdownr Nr/r0s rÚ _siftdown_maxr<sC€à‰i€Gð ‹.ؘ1‘W ‘Nˆ Ø‘ˆØ Ó Ø�‰I؈CÙ Ø Øˆ‚Ircóº•[U5nUnXnSU-S-nXR:a-US-nXb:a XX:dUnXX'UnSU-S-nXR:aM-X@U'[XU5 g)zMaxheap variant of _siftupr r N)rr<r7s rr(r('s€ä �‹Y€FØ€H؉i€Gà�‰u�q‰y€HØ Ó à˜a‘<ˆØ Ó  T¡^°d±nÓ%D؈Hà‘Nˆ‰ ؈Ø�S‘5˜1‘9ˆð Õ ðˆ�IÜ�$ #Õ&rNF©ÚkeyÚreversec'ó># •/nURnU(a[n[n[nSnO[n[ n[ nSnUc£[[[U55H$upšU Rn U"U "5X˜-U /5 M& U"U5 [U5S:”a#US=upÉp½U v• U "5U S'U"X=5 M!U(a USupÉn U v• U RShv•N g[[[U55H,upšU Rn U "5n U"U"U 5X˜-XË/5 M. U"U5 [U5S:”a0US=upépËn U v• U "5n U"U 5U S'XÍS'U"X=5 M.U(a!USupépËU v• U RShv•N gg![a GMQf=f![a U"U5 Of=f[U5S:”aGM@GNNü![a Míf=f![a U"U5 Of=f[U5S:”aMÓN¤N�7f)aCMerge multiple sorted inputs into a single sorted output. Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] If *key* is not None, applies a key function to each element to determine its sort order. >>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len)) ['dog', 'cat', 'fish', 'horse', 'kangaroo'] éÿÿÿÿr Nr r )r r-r)r+rrrÚ enumerateÚmapÚiterÚ__next__Ú StopIterationrÚ__self__)r?r@Ú iterablesÚhÚh_appendÚ_heapifyÚ_heappopÚ _heapreplaceÚ directionÚorderÚitÚnextÚvalueÚsÚ key_values rrr<s7é€ð$ €AØ�x‰x€HæÜˆÜˆÜ'ˆ ؉ äˆÜˆÜ"ˆ ؈ à �{Ü"¤3¤t¨YÓ#7Ö8‰IˆEð Ø—{‘{�Ù™$›& %Ñ"3°TÐ:Ö;ñ9ñ �Œ Ü�!‹f�q‹jð ØØ-.¨q©TÐ1Ñ&�E $Ø’KÙ›6�A�a‘DÙ  Ô&ñ ö à!" 1¡Ñ ˆE˜$ØŠKØ—}‘}× $Ð $Øäœs¤4¨Ó3Ö4‰ ˆð Ø—;‘;ˆDÙ“FˆEÙ ‘c˜%“j %Ñ"3°UÐAÖ Bñ 5ñ ˆQ„KÜ ˆa‹&�1‹*ð ØØ45°a±DÐ8Ñ-�  %°Ø’ Ù›�Ù˜5“z��!‘Ø�!‘Ù˜QÔ"ñ ö Ø()¨!©Ñ%ˆ ˜%ØŠ Ø—=‘=× Ñ ð øôM!ó Ûð ûô!ó Ù˜– ð úô�!‹f�q�jˆjñ %øôó Ú ð ûôó Ù �QŽKð úô ˆa‹&�1Ž*ñ !ùsº‚A HÁ#F ÂHÂ"F2Â?"HÃ!GÃ"#HÄ&G Ä,HÅ/G1Å7"HÆHÆHÆ F/Æ*HÆ.F/Æ/HÆ2GÇHÇGÇHÇHÇ G.Ç*HÇ-G.Ç.HÇ1HÈHÈHÈHÈHcó¼•US:Xa([U5n[5n[X4US9nXTLa/$U/$[U5nX:¼a [ XS9SU$Uc¦[U5n[[U5U5VVs/sHupxX‡4PM nnnU(dU$[U5 USSn Un [n UH nX‰:dM U "XXU 45 USupœU S- n M" UR5 UVV s/sHupŠUPM sn n$[U5n[[U5U5VVs/sHupxU"U5Xx4PM nnnU(dU$[U5 USSn Un [n UH)nU"U5n XÙ:dMU "X]X¨45 USupœnU S- n M+ UR5 UV V Vs/sHupÚoˆPM snn n $![ [ 4a GNtf=fs snnfs sn nfs snnfs snn n f)zZFind the n smallest elements in a dataset. Equivalent to: sorted(iterable, key=key)[:n] r ©Údefaultr?)r?Nr ) rEÚobjectÚminrÚsortedÚ TypeErrorÚAttributeErrorÚzipr"r-r+Úsort©r%Úiterabler?rQÚsentinelÚresultÚsizer&ÚelemÚtoprPrNÚ_orderÚkÚ_elems rrrÏs€ð ˆAƒvÜ �(‹^ˆÜ“8ˆÜ�R¨sÑ3ˆØÒ'ˆrÐ5¨f¨XÐ5ð1Ü�8‹}ˆð ‹9ܘ(Ñ,¨R¨aÐ0Ð 0ð ð �{Ü �(‹^ˆô,/¬u°Q«x¸Ô+<Ô=Ò+<¡ �4“)Ñ+<ˆÑ=ÞØˆMÜ�VÔØ�Q‰i˜‰lˆØˆÜ'ˆ ÛˆDØ�zÙ˜V¨E ]Ô3Ø$ Q™i‘ �ؘ‘ ’ñ ð � ‰ Œ Ù*0Ô1ª&™˜$“©&Ò1Ð1ô ˆh‹€BÜ25´e¸A³hÀÔ2CÔ DÒ2C¡w q‰s�4‹y˜!Ó"Ñ2C€FÑ DÞ Øˆ Ü�ÔØ �‰)�A‰,€CØ €EÜ#€LÛˆÙ �‹IˆØ �7Ù ˜ UÐ!1Ô 2Ø!'¨¡Ñ ˆC˜Ø �Q‰JŠEñ ð  ‡K�K„MÙ)/Õ 0ªÑ%�a ŠD©Ó 0Ð0øôU ”~Ð &ó Ú ð üó>ùó2ùóEùô 1s)° F.Á3GÃ$G ÄGÆGÆ.GÇGcóÊ•US:Xa([U5n[5n[X4US9nXTLa/$U/$[U5nX:¼a [ XSS9SU$Uc©[U5n[[SU*S5U5VVs/sHupxX‡4PM nnnU(dU$[U5 USSn U*n [n UH nX˜:dM U "XXU 45 USupœU S-n M" URSS9 UVV s/sHupŠUPM sn n$[U5n[[SU*S5U5VVs/sHupxU"U5Xx4PM nnnU(dU$[U5 USSn U*n [n UH)nU"U5n X�:dMU "X]X¨45 USupœnU S-n M+ URSS9 UV V Vs/sHupÚoˆPM snn n $![ [ 4a GNzf=fs snnfs sn nfs snnfs snn n f) zgFind the n largest elements in a dataset. Equivalent to: sorted(iterable, key=key, reverse=True)[:n] r rWTr>Nr rB)r@) rErYÚmaxrr[r\r]r^r"rrr_r`s rrr s€ð ˆAƒvÜ �(‹^ˆÜ“8ˆÜ�R¨sÑ3ˆØÒ'ˆrÐ5¨f¨XÐ5ð?Ü�8‹}ˆð ‹9ܘ(°TÑ:¸2¸AÐ>Ð >ð ð �{Ü �(‹^ˆÜ+.¬u°Q¸¸¸BÓ/?ÀÔ+DÔEÒ+D¡ �4“)Ñ+DˆÑEÞØˆMÜ�ŒØ�Q‰i˜‰lˆØ�ˆÜ"ˆ ÛˆDØ�zÙ˜V¨E ]Ô3Ø$ Q™i‘ �ؘ‘ ’ñ ð � ‰ ˜Dˆ Ñ!Ù*0Ô1ª&™˜$“©&Ò1Ð1ô ˆh‹€BÜ25´e¸AÀ¸rÀ2Ó6FÈÔ2KÔ LÒ2K¡w q‰s�4‹y˜!Ó"Ñ2K€FÑ LÞ Øˆ Ü ˆF„OØ �‰)�A‰,€CØ ˆB€EÜ€LÛˆÙ �‹IˆØ �7Ù ˜ UÐ!1Ô 2Ø!'¨¡Ñ ˆC˜Ø �Q‰JŠEñ ð  ‡K�K˜€KÑÙ)/Õ 0ªÑ%�a ŠD©Ó 0Ð0øôQ ”~Ð &ó Ú ð üóFùó2ùóMùô 1s)° F5Á7G Ã(GÄ GÆ"GÆ5G ÇG r )Ú*)r+)r-)r)Ú__main__)N)Ú__doc__Ú __about__Ú__all__rrrr rr)r+r-rrr<r(rrrÚ_heapqÚ ImportErrorÚ__name__ÚdoctestÚprintÚtestmodr/rrÚrwsðñðD\ € ò| 3€ò$ò òò ò òòòò òj#ò( ò'ð*¨õN!ôf:1ôx81ðv Üð Ý'ð Ý#ð Ý#ð  ˆzÓãÙ ˆ'�/Š/Ó Õðøð!ó Ùð ûðó Ùð ûðó Ùð ûðó Ùð úsHÁA=ÁB Á BÁB!Á=BÂB BÂBÂBÂBÂ!B*Â)B*