Skip to content Skip to sidebar Skip to footer

Unusual Result From Heappop?

I have a simple heap defined as a list of lists. I was using heapop from the heapq module to extract the list with the smallest key (which I learnt is implicitly the first element

Solution 1:

The problem is that you are using heapq on a list that is not a heap. The documentation discusses using the heapify command, and that indeed works:

>>> import heapq
>>> from numpy import inf
>>> heap=[[0, 0, 0], [inf, 1, 1], [inf, 2, 2], [5, 3, 3], [inf, 4, 4]]
>>> heapq.heapify(heap)
>>> heap
[[0, 0, 0], [5, 3, 3], [inf, 2, 2], [inf, 1, 1], [inf, 4, 4]]
>>> heapq.heappop(heap)
[0, 0, 0]
>>> heapq.heappop(heap)
[5, 3, 3]
>>> heapq.heappop(heap)
[inf, 1, 1]
>>> heapq.heappop(heap)
[inf, 2, 2]
>>> heapq.heappop(heap)
[inf, 4, 4]

Post a Comment for "Unusual Result From Heappop?"