+++ /dev/null
-# -*- coding: latin-1 -*-\r
-\r
-"""Heap queue algorithm (a.k.a. priority queue).\r
-\r
-Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\r
-all k, counting elements from 0. For the sake of comparison,\r
-non-existing elements are considered to be infinite. The interesting\r
-property of a heap is that a[0] is always its smallest element.\r
-\r
-Usage:\r
-\r
-heap = [] # creates an empty heap\r
-heappush(heap, item) # pushes a new item on the heap\r
-item = heappop(heap) # pops the smallest item from the heap\r
-item = heap[0] # smallest item on the heap without popping it\r
-heapify(x) # transforms list into a heap, in-place, in linear time\r
-item = heapreplace(heap, item) # pops and returns smallest item, and adds\r
- # new item; the heap size is unchanged\r
-\r
-Our API differs from textbook heap algorithms as follows:\r
-\r
-- We use 0-based indexing. This makes the relationship between the\r
- index for a node and the indexes for its children slightly less\r
- obvious, but is more suitable since Python uses 0-based indexing.\r
-\r
-- Our heappop() method returns the smallest item, not the largest.\r
-\r
-These two make it possible to view the heap as a regular Python list\r
-without surprises: heap[0] is the smallest item, and heap.sort()\r
-maintains the heap invariant!\r
-"""\r
-\r
-# Original code by Kevin O'Connor, augmented by Tim Peters and Raymond Hettinger\r
-\r
-__about__ = """Heap queues\r
-\r
-[explanation by François Pinard]\r
-\r
-Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\r
-all k, counting elements from 0. For the sake of comparison,\r
-non-existing elements are considered to be infinite. The interesting\r
-property of a heap is that a[0] is always its smallest element.\r
-\r
-The strange invariant above is meant to be an efficient memory\r
-representation for a tournament. The numbers below are `k', not a[k]:\r
-\r
- 0\r
-\r
- 1 2\r
-\r
- 3 4 5 6\r
-\r
- 7 8 9 10 11 12 13 14\r
-\r
- 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\r
-\r
-\r
-In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\r
-an usual binary tournament we see in sports, each cell is the winner\r
-over the two cells it tops, and we can trace the winner down the tree\r
-to see all opponents s/he had. However, in many computer applications\r
-of such tournaments, we do not need to trace the history of a winner.\r
-To be more memory efficient, when a winner is promoted, we try to\r
-replace it by something else at a lower level, and the rule becomes\r
-that a cell and the two cells it tops contain three different items,\r
-but the top cell "wins" over the two topped cells.\r
-\r
-If this heap invariant is protected at all time, index 0 is clearly\r
-the overall winner. The simplest algorithmic way to remove it and\r
-find the "next" winner is to move some loser (let's say cell 30 in the\r
-diagram above) into the 0 position, and then percolate this new 0 down\r
-the tree, exchanging values, until the invariant is re-established.\r
-This is clearly logarithmic on the total number of items in the tree.\r
-By iterating over all items, you get an O(n ln n) sort.\r
-\r
-A nice feature of this sort is that you can efficiently insert new\r
-items while the sort is going on, provided that the inserted items are\r
-not "better" than the last 0'th element you extracted. This is\r
-especially useful in simulation contexts, where the tree holds all\r
-incoming events, and the "win" condition means the smallest scheduled\r
-time. When an event schedule other events for execution, they are\r
-scheduled into the future, so they can easily go into the heap. So, a\r
-heap is a good structure for implementing schedulers (this is what I\r
-used for my MIDI sequencer :-).\r
-\r
-Various structures for implementing schedulers have been extensively\r
-studied, and heaps are good for this, as they are reasonably speedy,\r
-the speed is almost constant, and the worst case is not much different\r
-than the average case. However, there are other representations which\r
-are more efficient overall, yet the worst cases might be terrible.\r
-\r
-Heaps are also very useful in big disk sorts. You most probably all\r
-know that a big sort implies producing "runs" (which are pre-sorted\r
-sequences, which size is usually related to the amount of CPU memory),\r
-followed by a merging passes for these runs, which merging is often\r
-very cleverly organised[1]. It is very important that the initial\r
-sort produces the longest runs possible. Tournaments are a good way\r
-to that. If, using all the memory available to hold a tournament, you\r
-replace and percolate items that happen to fit the current run, you'll\r
-produce runs which are twice the size of the memory for random input,\r
-and much better for input fuzzily ordered.\r
-\r
-Moreover, if you output the 0'th item on disk and get an input which\r
-may not fit in the current tournament (because the value "wins" over\r
-the last output value), it cannot fit in the heap, so the size of the\r
-heap decreases. The freed memory could be cleverly reused immediately\r
-for progressively building a second heap, which grows at exactly the\r
-same rate the first heap is melting. When the first heap completely\r
-vanishes, you switch heaps and start a new run. Clever and quite\r
-effective!\r
-\r
-In a word, heaps are useful memory structures to know. I use them in\r
-a few applications, and I think it is good to keep a `heap' module\r
-around. :-)\r
-\r
---------------------\r
-[1] The disk balancing algorithms which are current, nowadays, are\r
-more annoying than clever, and this is a consequence of the seeking\r
-capabilities of the disks. On devices which cannot seek, like big\r
-tape drives, the story was quite different, and one had to be very\r
-clever to ensure (far in advance) that each tape movement will be the\r
-most effective possible (that is, will best participate at\r
-"progressing" the merge). Some tapes were even able to read\r
-backwards, and this was also used to avoid the rewinding time.\r
-Believe me, real good tape sorts were quite spectacular to watch!\r
-From all times, sorting has always been a Great Art! :-)\r
-"""\r
-\r
-__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',\r
- 'nlargest', 'nsmallest', 'heappushpop']\r
-\r
-from itertools import islice, count, imap, izip, tee, chain\r
-from operator import itemgetter\r
-\r
-def cmp_lt(x, y):\r
- # Use __lt__ if available; otherwise, try __le__.\r
- # In Py3.x, only __lt__ will be called.\r
- return (x < y) if hasattr(x, '__lt__') else (not y <= x)\r
-\r
-def heappush(heap, item):\r
- """Push item onto heap, maintaining the heap invariant."""\r
- heap.append(item)\r
- _siftdown(heap, 0, len(heap)-1)\r
-\r
-def heappop(heap):\r
- """Pop the smallest item off the heap, maintaining the heap invariant."""\r
- lastelt = heap.pop() # raises appropriate IndexError if heap is empty\r
- if heap:\r
- returnitem = heap[0]\r
- heap[0] = lastelt\r
- _siftup(heap, 0)\r
- else:\r
- returnitem = lastelt\r
- return returnitem\r
-\r
-def heapreplace(heap, item):\r
- """Pop and return the current smallest value, and add the new item.\r
-\r
- This is more efficient than heappop() followed by heappush(), and can be\r
- more appropriate when using a fixed-size heap. Note that the value\r
- returned may be larger than item! That constrains reasonable uses of\r
- this routine unless written as part of a conditional replacement:\r
-\r
- if item > heap[0]:\r
- item = heapreplace(heap, item)\r
- """\r
- returnitem = heap[0] # raises appropriate IndexError if heap is empty\r
- heap[0] = item\r
- _siftup(heap, 0)\r
- return returnitem\r
-\r
-def heappushpop(heap, item):\r
- """Fast version of a heappush followed by a heappop."""\r
- if heap and cmp_lt(heap[0], item):\r
- item, heap[0] = heap[0], item\r
- _siftup(heap, 0)\r
- return item\r
-\r
-def heapify(x):\r
- """Transform list into a heap, in-place, in O(len(x)) time."""\r
- n = len(x)\r
- # Transform bottom-up. The largest index there's any point to looking at\r
- # is the largest with a child index in-range, so must have 2*i + 1 < n,\r
- # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so\r
- # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is\r
- # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.\r
- for i in reversed(xrange(n//2)):\r
- _siftup(x, i)\r
-\r
-def _heappushpop_max(heap, item):\r
- """Maxheap version of a heappush followed by a heappop."""\r
- if heap and cmp_lt(item, heap[0]):\r
- item, heap[0] = heap[0], item\r
- _siftup_max(heap, 0)\r
- return item\r
-\r
-def _heapify_max(x):\r
- """Transform list into a maxheap, in-place, in O(len(x)) time."""\r
- n = len(x)\r
- for i in reversed(range(n//2)):\r
- _siftup_max(x, i)\r
-\r
-def nlargest(n, iterable):\r
- """Find the n largest elements in a dataset.\r
-\r
- Equivalent to: sorted(iterable, reverse=True)[:n]\r
- """\r
- if n < 0:\r
- return []\r
- it = iter(iterable)\r
- result = list(islice(it, n))\r
- if not result:\r
- return result\r
- heapify(result)\r
- _heappushpop = heappushpop\r
- for elem in it:\r
- _heappushpop(result, elem)\r
- result.sort(reverse=True)\r
- return result\r
-\r
-def nsmallest(n, iterable):\r
- """Find the n smallest elements in a dataset.\r
-\r
- Equivalent to: sorted(iterable)[:n]\r
- """\r
- if n < 0:\r
- return []\r
- it = iter(iterable)\r
- result = list(islice(it, n))\r
- if not result:\r
- return result\r
- _heapify_max(result)\r
- _heappushpop = _heappushpop_max\r
- for elem in it:\r
- _heappushpop(result, elem)\r
- result.sort()\r
- return result\r
-\r
-# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos\r
-# is the index of a leaf with a possibly out-of-order value. Restore the\r
-# heap invariant.\r
-def _siftdown(heap, startpos, pos):\r
- newitem = heap[pos]\r
- # Follow the path to the root, moving parents down until finding a place\r
- # newitem fits.\r
- while pos > startpos:\r
- parentpos = (pos - 1) >> 1\r
- parent = heap[parentpos]\r
- if cmp_lt(newitem, parent):\r
- heap[pos] = parent\r
- pos = parentpos\r
- continue\r
- break\r
- heap[pos] = newitem\r
-\r
-# The child indices of heap index pos are already heaps, and we want to make\r
-# a heap at index pos too. We do this by bubbling the smaller child of\r
-# pos up (and so on with that child's children, etc) until hitting a leaf,\r
-# then using _siftdown to move the oddball originally at index pos into place.\r
-#\r
-# We *could* break out of the loop as soon as we find a pos where newitem <=\r
-# both its children, but turns out that's not a good idea, and despite that\r
-# many books write the algorithm that way. During a heap pop, the last array\r
-# element is sifted in, and that tends to be large, so that comparing it\r
-# against values starting from the root usually doesn't pay (= usually doesn't\r
-# get us out of the loop early). See Knuth, Volume 3, where this is\r
-# explained and quantified in an exercise.\r
-#\r
-# Cutting the # of comparisons is important, since these routines have no\r
-# way to extract "the priority" from an array element, so that intelligence\r
-# is likely to be hiding in custom __cmp__ methods, or in array elements\r
-# storing (priority, record) tuples. Comparisons are thus potentially\r
-# expensive.\r
-#\r
-# On random arrays of length 1000, making this change cut the number of\r
-# comparisons made by heapify() a little, and those made by exhaustive\r
-# heappop() a lot, in accord with theory. Here are typical results from 3\r
-# runs (3 just to demonstrate how small the variance is):\r
-#\r
-# Compares needed by heapify Compares needed by 1000 heappops\r
-# -------------------------- --------------------------------\r
-# 1837 cut to 1663 14996 cut to 8680\r
-# 1855 cut to 1659 14966 cut to 8678\r
-# 1847 cut to 1660 15024 cut to 8703\r
-#\r
-# Building the heap by using heappush() 1000 times instead required\r
-# 2198, 2148, and 2219 compares: heapify() is more efficient, when\r
-# you can use it.\r
-#\r
-# The total compares needed by list.sort() on the same lists were 8627,\r
-# 8627, and 8632 (this should be compared to the sum of heapify() and\r
-# heappop() compares): list.sort() is (unsurprisingly!) more efficient\r
-# for sorting.\r
-\r
-def _siftup(heap, pos):\r
- endpos = len(heap)\r
- startpos = pos\r
- newitem = heap[pos]\r
- # Bubble up the smaller child until hitting a leaf.\r
- childpos = 2*pos + 1 # leftmost child position\r
- while childpos < endpos:\r
- # Set childpos to index of smaller child.\r
- rightpos = childpos + 1\r
- if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):\r
- childpos = rightpos\r
- # Move the smaller child up.\r
- heap[pos] = heap[childpos]\r
- pos = childpos\r
- childpos = 2*pos + 1\r
- # The leaf at pos is empty now. Put newitem there, and bubble it up\r
- # to its final resting place (by sifting its parents down).\r
- heap[pos] = newitem\r
- _siftdown(heap, startpos, pos)\r
-\r
-def _siftdown_max(heap, startpos, pos):\r
- 'Maxheap variant of _siftdown'\r
- newitem = heap[pos]\r
- # Follow the path to the root, moving parents down until finding a place\r
- # newitem fits.\r
- while pos > startpos:\r
- parentpos = (pos - 1) >> 1\r
- parent = heap[parentpos]\r
- if cmp_lt(parent, newitem):\r
- heap[pos] = parent\r
- pos = parentpos\r
- continue\r
- break\r
- heap[pos] = newitem\r
-\r
-def _siftup_max(heap, pos):\r
- 'Maxheap variant of _siftup'\r
- endpos = len(heap)\r
- startpos = pos\r
- newitem = heap[pos]\r
- # Bubble up the larger child until hitting a leaf.\r
- childpos = 2*pos + 1 # leftmost child position\r
- while childpos < endpos:\r
- # Set childpos to index of larger child.\r
- rightpos = childpos + 1\r
- if rightpos < endpos and not cmp_lt(heap[rightpos], heap[childpos]):\r
- childpos = rightpos\r
- # Move the larger child up.\r
- heap[pos] = heap[childpos]\r
- pos = childpos\r
- childpos = 2*pos + 1\r
- # The leaf at pos is empty now. Put newitem there, and bubble it up\r
- # to its final resting place (by sifting its parents down).\r
- heap[pos] = newitem\r
- _siftdown_max(heap, startpos, pos)\r
-\r
-# If available, use C implementation\r
-try:\r
- from _heapq import *\r
-except ImportError:\r
- pass\r
-\r
-def merge(*iterables):\r
- '''Merge multiple sorted inputs into a single sorted output.\r
-\r
- Similar to sorted(itertools.chain(*iterables)) but returns a generator,\r
- does not pull the data into memory all at once, and assumes that each of\r
- the input streams is already sorted (smallest to largest).\r
-\r
- >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))\r
- [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]\r
-\r
- '''\r
- _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration\r
- _len = len\r
-\r
- h = []\r
- h_append = h.append\r
- for itnum, it in enumerate(map(iter, iterables)):\r
- try:\r
- next = it.next\r
- h_append([next(), itnum, next])\r
- except _StopIteration:\r
- pass\r
- heapify(h)\r
-\r
- while _len(h) > 1:\r
- try:\r
- while 1:\r
- v, itnum, next = s = h[0]\r
- yield v\r
- s[0] = next() # raises StopIteration when exhausted\r
- _heapreplace(h, s) # restore heap condition\r
- except _StopIteration:\r
- _heappop(h) # remove empty iterator\r
- if h:\r
- # fast case when only a single iterator remains\r
- v, itnum, next = h[0]\r
- yield v\r
- for v in next.__self__:\r
- yield v\r
-\r
-# Extend the implementations of nsmallest and nlargest to use a key= argument\r
-_nsmallest = nsmallest\r
-def nsmallest(n, iterable, key=None):\r
- """Find the n smallest elements in a dataset.\r
-\r
- Equivalent to: sorted(iterable, key=key)[:n]\r
- """\r
- # Short-cut for n==1 is to use min() when len(iterable)>0\r
- if n == 1:\r
- it = iter(iterable)\r
- head = list(islice(it, 1))\r
- if not head:\r
- return []\r
- if key is None:\r
- return [min(chain(head, it))]\r
- return [min(chain(head, it), key=key)]\r
-\r
- # When n>=size, it's faster to use sorted()\r
- try:\r
- size = len(iterable)\r
- except (TypeError, AttributeError):\r
- pass\r
- else:\r
- if n >= size:\r
- return sorted(iterable, key=key)[:n]\r
-\r
- # When key is none, use simpler decoration\r
- if key is None:\r
- it = izip(iterable, count()) # decorate\r
- result = _nsmallest(n, it)\r
- return map(itemgetter(0), result) # undecorate\r
-\r
- # General case, slowest method\r
- in1, in2 = tee(iterable)\r
- it = izip(imap(key, in1), count(), in2) # decorate\r
- result = _nsmallest(n, it)\r
- return map(itemgetter(2), result) # undecorate\r
-\r
-_nlargest = nlargest\r
-def nlargest(n, iterable, key=None):\r
- """Find the n largest elements in a dataset.\r
-\r
- Equivalent to: sorted(iterable, key=key, reverse=True)[:n]\r
- """\r
-\r
- # Short-cut for n==1 is to use max() when len(iterable)>0\r
- if n == 1:\r
- it = iter(iterable)\r
- head = list(islice(it, 1))\r
- if not head:\r
- return []\r
- if key is None:\r
- return [max(chain(head, it))]\r
- return [max(chain(head, it), key=key)]\r
-\r
- # When n>=size, it's faster to use sorted()\r
- try:\r
- size = len(iterable)\r
- except (TypeError, AttributeError):\r
- pass\r
- else:\r
- if n >= size:\r
- return sorted(iterable, key=key, reverse=True)[:n]\r
-\r
- # When key is none, use simpler decoration\r
- if key is None:\r
- it = izip(iterable, count(0,-1)) # decorate\r
- result = _nlargest(n, it)\r
- return map(itemgetter(0), result) # undecorate\r
-\r
- # General case, slowest method\r
- in1, in2 = tee(iterable)\r
- it = izip(imap(key, in1), count(0,-1), in2) # decorate\r
- result = _nlargest(n, it)\r
- return map(itemgetter(2), result) # undecorate\r
-\r
-if __name__ == "__main__":\r
- # Simple sanity test\r
- heap = []\r
- data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]\r
- for item in data:\r
- heappush(heap, item)\r
- sort = []\r
- while heap:\r
- sort.append(heappop(heap))\r
- print sort\r
-\r
- import doctest\r
- doctest.testmod()\r