Home > database >  Python HeapPushPop not popping minimum element
Python HeapPushPop not popping minimum element

Time:12-30

I feel like I must be misunderstanding heappushpop because I can't make out why this is happening.

sequence = [2, 6, 4, 5, 8]
result = []
x = [3, -1]
result.append(heapq.heappushpop(x, sequence[0]))

Should this not push 2 onto the heap x and pop -1? I'm getting the 2 pushed and popped.

CodePudding user response:

This happens because you didn't work with a min heap to start with.

x is not a min heap. You cannot expect a heapq function that works on a heap to give a sensible result when the list you pass to it is not a heap.

So first do:

heapq.heapify(x)

Test:

import heapq

x = [3, -1]
heapq.heapify(x)
print(heapq.heappushpop(x, 2))  # outputs -1
print(x)  # outputs [2, 3]
  • Related