diff options
author | Raymond Hettinger <python@rcn.com> | 2008-03-13 19:03:51 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2008-03-13 19:03:51 (GMT) |
commit | 53bdf093437349907807da9143f9c2bdcea9ab3a (patch) | |
tree | 11b94ee0f3c83f57e7870a4abfc44760cccdeef8 /Lib/heapq.py | |
parent | 431f0294867b474525a2f91e03101d1462f56801 (diff) | |
download | cpython-53bdf093437349907807da9143f9c2bdcea9ab3a.zip cpython-53bdf093437349907807da9143f9c2bdcea9ab3a.tar.gz cpython-53bdf093437349907807da9143f9c2bdcea9ab3a.tar.bz2 |
Issue 2274: Add heapq.heappushpop().
Diffstat (limited to 'Lib/heapq.py')
-rw-r--r-- | Lib/heapq.py | 11 |
1 files changed, 9 insertions, 2 deletions
diff --git a/Lib/heapq.py b/Lib/heapq.py index 39e3800..23f5fcb 100644 --- a/Lib/heapq.py +++ b/Lib/heapq.py @@ -127,7 +127,7 @@ From all times, sorting has always been a Great Art! :-) """ __all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', - 'nlargest', 'nsmallest'] + 'nlargest', 'nsmallest', 'heappushpop'] from itertools import islice, repeat, count, imap, izip, tee from operator import itemgetter, neg @@ -165,6 +165,13 @@ def heapreplace(heap, item): _siftup(heap, 0) return returnitem +def heappushpop(heap, item): + """Fast version of a heappush followed by a heappop.""" + if heap and item > heap[0]: + item, heap[0] = heap[0], item + _siftup(heap, 0) + return item + def heapify(x): """Transform list into a heap, in-place, in O(len(heap)) time.""" n = len(x) @@ -304,7 +311,7 @@ def _siftup(heap, pos): # If available, use C implementation try: - from _heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest + from _heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest, heappushpop except ImportError: pass |