17db96d56Sopenharmony_ci:mod:`heapq` --- Heap queue algorithm 27db96d56Sopenharmony_ci===================================== 37db96d56Sopenharmony_ci 47db96d56Sopenharmony_ci.. module:: heapq 57db96d56Sopenharmony_ci :synopsis: Heap queue algorithm (a.k.a. priority queue). 67db96d56Sopenharmony_ci 77db96d56Sopenharmony_ci.. moduleauthor:: Kevin O'Connor 87db96d56Sopenharmony_ci.. sectionauthor:: Guido van Rossum <guido@python.org> 97db96d56Sopenharmony_ci.. sectionauthor:: François Pinard 107db96d56Sopenharmony_ci.. sectionauthor:: Raymond Hettinger 117db96d56Sopenharmony_ci 127db96d56Sopenharmony_ci**Source code:** :source:`Lib/heapq.py` 137db96d56Sopenharmony_ci 147db96d56Sopenharmony_ci-------------- 157db96d56Sopenharmony_ci 167db96d56Sopenharmony_ciThis module provides an implementation of the heap queue algorithm, also known 177db96d56Sopenharmony_cias the priority queue algorithm. 187db96d56Sopenharmony_ci 197db96d56Sopenharmony_ciHeaps are binary trees for which every parent node has a value less than or 207db96d56Sopenharmony_ciequal to any of its children. This implementation uses arrays for which 217db96d56Sopenharmony_ci``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting 227db96d56Sopenharmony_cielements from zero. For the sake of comparison, non-existing elements are 237db96d56Sopenharmony_ciconsidered to be infinite. The interesting property of a heap is that its 247db96d56Sopenharmony_cismallest element is always the root, ``heap[0]``. 257db96d56Sopenharmony_ci 267db96d56Sopenharmony_ciThe API below differs from textbook heap algorithms in two aspects: (a) We use 277db96d56Sopenharmony_cizero-based indexing. This makes the relationship between the index for a node 287db96d56Sopenharmony_ciand the indexes for its children slightly less obvious, but is more suitable 297db96d56Sopenharmony_cisince Python uses zero-based indexing. (b) Our pop method returns the smallest 307db96d56Sopenharmony_ciitem, not the largest (called a "min heap" in textbooks; a "max heap" is more 317db96d56Sopenharmony_cicommon in texts because of its suitability for in-place sorting). 327db96d56Sopenharmony_ci 337db96d56Sopenharmony_ciThese two make it possible to view the heap as a regular Python list without 347db96d56Sopenharmony_cisurprises: ``heap[0]`` is the smallest item, and ``heap.sort()`` maintains the 357db96d56Sopenharmony_ciheap invariant! 367db96d56Sopenharmony_ci 377db96d56Sopenharmony_ciTo create a heap, use a list initialized to ``[]``, or you can transform a 387db96d56Sopenharmony_cipopulated list into a heap via function :func:`heapify`. 397db96d56Sopenharmony_ci 407db96d56Sopenharmony_ciThe following functions are provided: 417db96d56Sopenharmony_ci 427db96d56Sopenharmony_ci 437db96d56Sopenharmony_ci.. function:: heappush(heap, item) 447db96d56Sopenharmony_ci 457db96d56Sopenharmony_ci Push the value *item* onto the *heap*, maintaining the heap invariant. 467db96d56Sopenharmony_ci 477db96d56Sopenharmony_ci 487db96d56Sopenharmony_ci.. function:: heappop(heap) 497db96d56Sopenharmony_ci 507db96d56Sopenharmony_ci Pop and return the smallest item from the *heap*, maintaining the heap 517db96d56Sopenharmony_ci invariant. If the heap is empty, :exc:`IndexError` is raised. To access the 527db96d56Sopenharmony_ci smallest item without popping it, use ``heap[0]``. 537db96d56Sopenharmony_ci 547db96d56Sopenharmony_ci 557db96d56Sopenharmony_ci.. function:: heappushpop(heap, item) 567db96d56Sopenharmony_ci 577db96d56Sopenharmony_ci Push *item* on the heap, then pop and return the smallest item from the 587db96d56Sopenharmony_ci *heap*. The combined action runs more efficiently than :func:`heappush` 597db96d56Sopenharmony_ci followed by a separate call to :func:`heappop`. 607db96d56Sopenharmony_ci 617db96d56Sopenharmony_ci 627db96d56Sopenharmony_ci.. function:: heapify(x) 637db96d56Sopenharmony_ci 647db96d56Sopenharmony_ci Transform list *x* into a heap, in-place, in linear time. 657db96d56Sopenharmony_ci 667db96d56Sopenharmony_ci 677db96d56Sopenharmony_ci.. function:: heapreplace(heap, item) 687db96d56Sopenharmony_ci 697db96d56Sopenharmony_ci Pop and return the smallest item from the *heap*, and also push the new *item*. 707db96d56Sopenharmony_ci The heap size doesn't change. If the heap is empty, :exc:`IndexError` is raised. 717db96d56Sopenharmony_ci 727db96d56Sopenharmony_ci This one step operation is more efficient than a :func:`heappop` followed by 737db96d56Sopenharmony_ci :func:`heappush` and can be more appropriate when using a fixed-size heap. 747db96d56Sopenharmony_ci The pop/push combination always returns an element from the heap and replaces 757db96d56Sopenharmony_ci it with *item*. 767db96d56Sopenharmony_ci 777db96d56Sopenharmony_ci The value returned may be larger than the *item* added. If that isn't 787db96d56Sopenharmony_ci desired, consider using :func:`heappushpop` instead. Its push/pop 797db96d56Sopenharmony_ci combination returns the smaller of the two values, leaving the larger value 807db96d56Sopenharmony_ci on the heap. 817db96d56Sopenharmony_ci 827db96d56Sopenharmony_ci 837db96d56Sopenharmony_ciThe module also offers three general purpose functions based on heaps. 847db96d56Sopenharmony_ci 857db96d56Sopenharmony_ci 867db96d56Sopenharmony_ci.. function:: merge(*iterables, key=None, reverse=False) 877db96d56Sopenharmony_ci 887db96d56Sopenharmony_ci Merge multiple sorted inputs into a single sorted output (for example, merge 897db96d56Sopenharmony_ci timestamped entries from multiple log files). Returns an :term:`iterator` 907db96d56Sopenharmony_ci over the sorted values. 917db96d56Sopenharmony_ci 927db96d56Sopenharmony_ci Similar to ``sorted(itertools.chain(*iterables))`` but returns an iterable, does 937db96d56Sopenharmony_ci not pull the data into memory all at once, and assumes that each of the input 947db96d56Sopenharmony_ci streams is already sorted (smallest to largest). 957db96d56Sopenharmony_ci 967db96d56Sopenharmony_ci Has two optional arguments which must be specified as keyword arguments. 977db96d56Sopenharmony_ci 987db96d56Sopenharmony_ci *key* specifies a :term:`key function` of one argument that is used to 997db96d56Sopenharmony_ci extract a comparison key from each input element. The default value is 1007db96d56Sopenharmony_ci ``None`` (compare the elements directly). 1017db96d56Sopenharmony_ci 1027db96d56Sopenharmony_ci *reverse* is a boolean value. If set to ``True``, then the input elements 1037db96d56Sopenharmony_ci are merged as if each comparison were reversed. To achieve behavior similar 1047db96d56Sopenharmony_ci to ``sorted(itertools.chain(*iterables), reverse=True)``, all iterables must 1057db96d56Sopenharmony_ci be sorted from largest to smallest. 1067db96d56Sopenharmony_ci 1077db96d56Sopenharmony_ci .. versionchanged:: 3.5 1087db96d56Sopenharmony_ci Added the optional *key* and *reverse* parameters. 1097db96d56Sopenharmony_ci 1107db96d56Sopenharmony_ci 1117db96d56Sopenharmony_ci.. function:: nlargest(n, iterable, key=None) 1127db96d56Sopenharmony_ci 1137db96d56Sopenharmony_ci Return a list with the *n* largest elements from the dataset defined by 1147db96d56Sopenharmony_ci *iterable*. *key*, if provided, specifies a function of one argument that is 1157db96d56Sopenharmony_ci used to extract a comparison key from each element in *iterable* (for example, 1167db96d56Sopenharmony_ci ``key=str.lower``). Equivalent to: ``sorted(iterable, key=key, 1177db96d56Sopenharmony_ci reverse=True)[:n]``. 1187db96d56Sopenharmony_ci 1197db96d56Sopenharmony_ci 1207db96d56Sopenharmony_ci.. function:: nsmallest(n, iterable, key=None) 1217db96d56Sopenharmony_ci 1227db96d56Sopenharmony_ci Return a list with the *n* smallest elements from the dataset defined by 1237db96d56Sopenharmony_ci *iterable*. *key*, if provided, specifies a function of one argument that is 1247db96d56Sopenharmony_ci used to extract a comparison key from each element in *iterable* (for example, 1257db96d56Sopenharmony_ci ``key=str.lower``). Equivalent to: ``sorted(iterable, key=key)[:n]``. 1267db96d56Sopenharmony_ci 1277db96d56Sopenharmony_ci 1287db96d56Sopenharmony_ciThe latter two functions perform best for smaller values of *n*. For larger 1297db96d56Sopenharmony_civalues, it is more efficient to use the :func:`sorted` function. Also, when 1307db96d56Sopenharmony_ci``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max` 1317db96d56Sopenharmony_cifunctions. If repeated usage of these functions is required, consider turning 1327db96d56Sopenharmony_cithe iterable into an actual heap. 1337db96d56Sopenharmony_ci 1347db96d56Sopenharmony_ci 1357db96d56Sopenharmony_ciBasic Examples 1367db96d56Sopenharmony_ci-------------- 1377db96d56Sopenharmony_ci 1387db96d56Sopenharmony_ciA `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_ can be implemented by 1397db96d56Sopenharmony_cipushing all values onto a heap and then popping off the smallest values one at a 1407db96d56Sopenharmony_citime:: 1417db96d56Sopenharmony_ci 1427db96d56Sopenharmony_ci >>> def heapsort(iterable): 1437db96d56Sopenharmony_ci ... h = [] 1447db96d56Sopenharmony_ci ... for value in iterable: 1457db96d56Sopenharmony_ci ... heappush(h, value) 1467db96d56Sopenharmony_ci ... return [heappop(h) for i in range(len(h))] 1477db96d56Sopenharmony_ci ... 1487db96d56Sopenharmony_ci >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]) 1497db96d56Sopenharmony_ci [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 1507db96d56Sopenharmony_ci 1517db96d56Sopenharmony_ciThis is similar to ``sorted(iterable)``, but unlike :func:`sorted`, this 1527db96d56Sopenharmony_ciimplementation is not stable. 1537db96d56Sopenharmony_ci 1547db96d56Sopenharmony_ciHeap elements can be tuples. This is useful for assigning comparison values 1557db96d56Sopenharmony_ci(such as task priorities) alongside the main record being tracked:: 1567db96d56Sopenharmony_ci 1577db96d56Sopenharmony_ci >>> h = [] 1587db96d56Sopenharmony_ci >>> heappush(h, (5, 'write code')) 1597db96d56Sopenharmony_ci >>> heappush(h, (7, 'release product')) 1607db96d56Sopenharmony_ci >>> heappush(h, (1, 'write spec')) 1617db96d56Sopenharmony_ci >>> heappush(h, (3, 'create tests')) 1627db96d56Sopenharmony_ci >>> heappop(h) 1637db96d56Sopenharmony_ci (1, 'write spec') 1647db96d56Sopenharmony_ci 1657db96d56Sopenharmony_ci 1667db96d56Sopenharmony_ciPriority Queue Implementation Notes 1677db96d56Sopenharmony_ci----------------------------------- 1687db96d56Sopenharmony_ci 1697db96d56Sopenharmony_ciA `priority queue <https://en.wikipedia.org/wiki/Priority_queue>`_ is common use 1707db96d56Sopenharmony_cifor a heap, and it presents several implementation challenges: 1717db96d56Sopenharmony_ci 1727db96d56Sopenharmony_ci* Sort stability: how do you get two tasks with equal priorities to be returned 1737db96d56Sopenharmony_ci in the order they were originally added? 1747db96d56Sopenharmony_ci 1757db96d56Sopenharmony_ci* Tuple comparison breaks for (priority, task) pairs if the priorities are equal 1767db96d56Sopenharmony_ci and the tasks do not have a default comparison order. 1777db96d56Sopenharmony_ci 1787db96d56Sopenharmony_ci* If the priority of a task changes, how do you move it to a new position in 1797db96d56Sopenharmony_ci the heap? 1807db96d56Sopenharmony_ci 1817db96d56Sopenharmony_ci* Or if a pending task needs to be deleted, how do you find it and remove it 1827db96d56Sopenharmony_ci from the queue? 1837db96d56Sopenharmony_ci 1847db96d56Sopenharmony_ciA solution to the first two challenges is to store entries as 3-element list 1857db96d56Sopenharmony_ciincluding the priority, an entry count, and the task. The entry count serves as 1867db96d56Sopenharmony_cia tie-breaker so that two tasks with the same priority are returned in the order 1877db96d56Sopenharmony_cithey were added. And since no two entry counts are the same, the tuple 1887db96d56Sopenharmony_cicomparison will never attempt to directly compare two tasks. 1897db96d56Sopenharmony_ci 1907db96d56Sopenharmony_ciAnother solution to the problem of non-comparable tasks is to create a wrapper 1917db96d56Sopenharmony_ciclass that ignores the task item and only compares the priority field:: 1927db96d56Sopenharmony_ci 1937db96d56Sopenharmony_ci from dataclasses import dataclass, field 1947db96d56Sopenharmony_ci from typing import Any 1957db96d56Sopenharmony_ci 1967db96d56Sopenharmony_ci @dataclass(order=True) 1977db96d56Sopenharmony_ci class PrioritizedItem: 1987db96d56Sopenharmony_ci priority: int 1997db96d56Sopenharmony_ci item: Any=field(compare=False) 2007db96d56Sopenharmony_ci 2017db96d56Sopenharmony_ciThe remaining challenges revolve around finding a pending task and making 2027db96d56Sopenharmony_cichanges to its priority or removing it entirely. Finding a task can be done 2037db96d56Sopenharmony_ciwith a dictionary pointing to an entry in the queue. 2047db96d56Sopenharmony_ci 2057db96d56Sopenharmony_ciRemoving the entry or changing its priority is more difficult because it would 2067db96d56Sopenharmony_cibreak the heap structure invariants. So, a possible solution is to mark the 2077db96d56Sopenharmony_cientry as removed and add a new entry with the revised priority:: 2087db96d56Sopenharmony_ci 2097db96d56Sopenharmony_ci pq = [] # list of entries arranged in a heap 2107db96d56Sopenharmony_ci entry_finder = {} # mapping of tasks to entries 2117db96d56Sopenharmony_ci REMOVED = '<removed-task>' # placeholder for a removed task 2127db96d56Sopenharmony_ci counter = itertools.count() # unique sequence count 2137db96d56Sopenharmony_ci 2147db96d56Sopenharmony_ci def add_task(task, priority=0): 2157db96d56Sopenharmony_ci 'Add a new task or update the priority of an existing task' 2167db96d56Sopenharmony_ci if task in entry_finder: 2177db96d56Sopenharmony_ci remove_task(task) 2187db96d56Sopenharmony_ci count = next(counter) 2197db96d56Sopenharmony_ci entry = [priority, count, task] 2207db96d56Sopenharmony_ci entry_finder[task] = entry 2217db96d56Sopenharmony_ci heappush(pq, entry) 2227db96d56Sopenharmony_ci 2237db96d56Sopenharmony_ci def remove_task(task): 2247db96d56Sopenharmony_ci 'Mark an existing task as REMOVED. Raise KeyError if not found.' 2257db96d56Sopenharmony_ci entry = entry_finder.pop(task) 2267db96d56Sopenharmony_ci entry[-1] = REMOVED 2277db96d56Sopenharmony_ci 2287db96d56Sopenharmony_ci def pop_task(): 2297db96d56Sopenharmony_ci 'Remove and return the lowest priority task. Raise KeyError if empty.' 2307db96d56Sopenharmony_ci while pq: 2317db96d56Sopenharmony_ci priority, count, task = heappop(pq) 2327db96d56Sopenharmony_ci if task is not REMOVED: 2337db96d56Sopenharmony_ci del entry_finder[task] 2347db96d56Sopenharmony_ci return task 2357db96d56Sopenharmony_ci raise KeyError('pop from an empty priority queue') 2367db96d56Sopenharmony_ci 2377db96d56Sopenharmony_ci 2387db96d56Sopenharmony_ciTheory 2397db96d56Sopenharmony_ci------ 2407db96d56Sopenharmony_ci 2417db96d56Sopenharmony_ciHeaps are arrays for which ``a[k] <= a[2*k+1]`` and ``a[k] <= a[2*k+2]`` for all 2427db96d56Sopenharmony_ci*k*, counting elements from 0. For the sake of comparison, non-existing 2437db96d56Sopenharmony_cielements are considered to be infinite. The interesting property of a heap is 2447db96d56Sopenharmony_cithat ``a[0]`` is always its smallest element. 2457db96d56Sopenharmony_ci 2467db96d56Sopenharmony_ciThe strange invariant above is meant to be an efficient memory representation 2477db96d56Sopenharmony_cifor a tournament. The numbers below are *k*, not ``a[k]``:: 2487db96d56Sopenharmony_ci 2497db96d56Sopenharmony_ci 0 2507db96d56Sopenharmony_ci 2517db96d56Sopenharmony_ci 1 2 2527db96d56Sopenharmony_ci 2537db96d56Sopenharmony_ci 3 4 5 6 2547db96d56Sopenharmony_ci 2557db96d56Sopenharmony_ci 7 8 9 10 11 12 13 14 2567db96d56Sopenharmony_ci 2577db96d56Sopenharmony_ci 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 2587db96d56Sopenharmony_ci 2597db96d56Sopenharmony_ciIn the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In a usual 2607db96d56Sopenharmony_cibinary tournament we see in sports, each cell is the winner over the two cells 2617db96d56Sopenharmony_ciit tops, and we can trace the winner down the tree to see all opponents s/he 2627db96d56Sopenharmony_cihad. However, in many computer applications of such tournaments, we do not need 2637db96d56Sopenharmony_cito trace the history of a winner. To be more memory efficient, when a winner is 2647db96d56Sopenharmony_cipromoted, we try to replace it by something else at a lower level, and the rule 2657db96d56Sopenharmony_cibecomes that a cell and the two cells it tops contain three different items, but 2667db96d56Sopenharmony_cithe top cell "wins" over the two topped cells. 2677db96d56Sopenharmony_ci 2687db96d56Sopenharmony_ciIf this heap invariant is protected at all time, index 0 is clearly the overall 2697db96d56Sopenharmony_ciwinner. The simplest algorithmic way to remove it and find the "next" winner is 2707db96d56Sopenharmony_cito move some loser (let's say cell 30 in the diagram above) into the 0 position, 2717db96d56Sopenharmony_ciand then percolate this new 0 down the tree, exchanging values, until the 2727db96d56Sopenharmony_ciinvariant is re-established. This is clearly logarithmic on the total number of 2737db96d56Sopenharmony_ciitems in the tree. By iterating over all items, you get an O(n log n) sort. 2747db96d56Sopenharmony_ci 2757db96d56Sopenharmony_ciA nice feature of this sort is that you can efficiently insert new items while 2767db96d56Sopenharmony_cithe sort is going on, provided that the inserted items are not "better" than the 2777db96d56Sopenharmony_cilast 0'th element you extracted. This is especially useful in simulation 2787db96d56Sopenharmony_cicontexts, where the tree holds all incoming events, and the "win" condition 2797db96d56Sopenharmony_cimeans the smallest scheduled time. When an event schedules other events for 2807db96d56Sopenharmony_ciexecution, they are scheduled into the future, so they can easily go into the 2817db96d56Sopenharmony_ciheap. So, a heap is a good structure for implementing schedulers (this is what 2827db96d56Sopenharmony_ciI used for my MIDI sequencer :-). 2837db96d56Sopenharmony_ci 2847db96d56Sopenharmony_ciVarious structures for implementing schedulers have been extensively studied, 2857db96d56Sopenharmony_ciand heaps are good for this, as they are reasonably speedy, the speed is almost 2867db96d56Sopenharmony_ciconstant, and the worst case is not much different than the average case. 2877db96d56Sopenharmony_ciHowever, there are other representations which are more efficient overall, yet 2887db96d56Sopenharmony_cithe worst cases might be terrible. 2897db96d56Sopenharmony_ci 2907db96d56Sopenharmony_ciHeaps are also very useful in big disk sorts. You most probably all know that a 2917db96d56Sopenharmony_cibig sort implies producing "runs" (which are pre-sorted sequences, whose size is 2927db96d56Sopenharmony_ciusually related to the amount of CPU memory), followed by a merging passes for 2937db96d56Sopenharmony_cithese runs, which merging is often very cleverly organised [#]_. It is very 2947db96d56Sopenharmony_ciimportant that the initial sort produces the longest runs possible. Tournaments 2957db96d56Sopenharmony_ciare a good way to achieve that. If, using all the memory available to hold a 2967db96d56Sopenharmony_citournament, you replace and percolate items that happen to fit the current run, 2977db96d56Sopenharmony_ciyou'll produce runs which are twice the size of the memory for random input, and 2987db96d56Sopenharmony_cimuch better for input fuzzily ordered. 2997db96d56Sopenharmony_ci 3007db96d56Sopenharmony_ciMoreover, if you output the 0'th item on disk and get an input which may not fit 3017db96d56Sopenharmony_ciin the current tournament (because the value "wins" over the last output value), 3027db96d56Sopenharmony_ciit cannot fit in the heap, so the size of the heap decreases. The freed memory 3037db96d56Sopenharmony_cicould be cleverly reused immediately for progressively building a second heap, 3047db96d56Sopenharmony_ciwhich grows at exactly the same rate the first heap is melting. When the first 3057db96d56Sopenharmony_ciheap completely vanishes, you switch heaps and start a new run. Clever and 3067db96d56Sopenharmony_ciquite effective! 3077db96d56Sopenharmony_ci 3087db96d56Sopenharmony_ciIn a word, heaps are useful memory structures to know. I use them in a few 3097db96d56Sopenharmony_ciapplications, and I think it is good to keep a 'heap' module around. :-) 3107db96d56Sopenharmony_ci 3117db96d56Sopenharmony_ci.. rubric:: Footnotes 3127db96d56Sopenharmony_ci 3137db96d56Sopenharmony_ci.. [#] The disk balancing algorithms which are current, nowadays, are more annoying 3147db96d56Sopenharmony_ci than clever, and this is a consequence of the seeking capabilities of the disks. 3157db96d56Sopenharmony_ci On devices which cannot seek, like big tape drives, the story was quite 3167db96d56Sopenharmony_ci different, and one had to be very clever to ensure (far in advance) that each 3177db96d56Sopenharmony_ci tape movement will be the most effective possible (that is, will best 3187db96d56Sopenharmony_ci participate at "progressing" the merge). Some tapes were even able to read 3197db96d56Sopenharmony_ci backwards, and this was also used to avoid the rewinding time. Believe me, real 3207db96d56Sopenharmony_ci good tape sorts were quite spectacular to watch! From all times, sorting has 3217db96d56Sopenharmony_ci always been a Great Art! :-) 3227db96d56Sopenharmony_ci 323