For the example from the official heapq:
>>> heap = []
>>> data = [(1, 'J'), (4, 'N'), (3, 'H'), (2, 'O')]
>>> for item in data:
... heappush(heap, item)
...
>>> while heap:
... print(heappop(heap)[1])
J
O
H
N
I want to further implement an efficient selective_push such that
- selective_push((1, 'M')) is equivalent to heappush since 'M' is not in the heap
- selective_push((3.5, 'N')) is equivalent to heap[2]= (3.5, 'N'); heapify(heap) since 3.5<4
- selective_push((4.5, 'N')) does nothing since 4.5>4
The following implementation explains the goal but slow:
def selective_push(heap,s):
NotFound=True
for i in range(len(heap)): #linear search
if heap[i][1]==s[1]:
if s[0]<heap[i][0]:
heap[i]=s #replacement
heapify(heap)
NotFound=False
break
if NotFound:
heappush(heap,s)
I think it is slow due to the linear search, which ruins the log(n) complexity of heapq.push
. The replacement rate is low, but the linear search is always executed.