Commit 6b4702dd authored by Tim Peters's avatar Tim Peters

Added new heapreplace(heap, item) function, to pop (and return) the

currently-smallest value, and add item, in one gulp.  See the second
N-Best algorithm in the test suite for a natural use.
parent b6d6b61f
...@@ -14,6 +14,8 @@ heappush(heap, item) # pushes a new item on the heap ...@@ -14,6 +14,8 @@ heappush(heap, item) # pushes a new item on the heap
item = heappop(heap) # pops the smallest item from the heap item = heappop(heap) # pops the smallest item from the heap
item = heap[0] # smallest item on the heap without popping it item = heap[0] # smallest item on the heap without popping it
heapify(x) # transforms list into a heap, in-place, in linear time heapify(x) # transforms list into a heap, in-place, in linear time
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: Our API differs from textbook heap algorithms as follows:
...@@ -140,6 +142,22 @@ def heappop(heap): ...@@ -140,6 +142,22 @@ def heappop(heap):
returnitem = lastelt returnitem = lastelt
return returnitem return returnitem
def heapreplace(heap, item):
"""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.
"""
if heap:
returnitem = heap[0]
heap[0] = item
_siftup(heap, 0)
return returnitem
heap.pop() # raise IndexError
def heapify(x): def heapify(x):
"""Transform list into a heap, in-place, in O(len(heap)) time.""" """Transform list into a heap, in-place, in O(len(heap)) time."""
n = len(x) n = len(x)
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
from test.test_support import verify, vereq, verbose, TestFailed from test.test_support import verify, vereq, verbose, TestFailed
from heapq import heappush, heappop, heapify from heapq import heappush, heappop, heapify, heapreplace
import random import random
def check_invariant(heap): def check_invariant(heap):
...@@ -68,8 +68,7 @@ def test_main(): ...@@ -68,8 +68,7 @@ def test_main():
heapify(heap) heapify(heap)
for item in data[10:]: for item in data[10:]:
if item > heap[0]: # this gets rarer the longer we run if item > heap[0]: # this gets rarer the longer we run
heappop(heap) # we know heap[0] isn't in best 10 anymore heapreplace(heap, item)
heappush(heap, item)
vereq(list(heapiter(heap)), data_sorted[-10:]) vereq(list(heapiter(heap)), data_sorted[-10:])
# Make user happy # Make user happy
if verbose: if verbose:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment