问题
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 of the inner list). But in the following case, the pop operation seems to be giving unusual results.
Can someone explain why?
heap=[[0, 0, 0], [inf, 1, 1], [inf, 2, 2], [5, 3, 3], [inf, 4, 4]]
heapq.heappop(heap)
[0, 0, 0]
heapq.heappop(heap)
[inf, 1, 1]
heapq.heappop(heap)
[5, 3, 3]
heapq.heappop(heap)
[inf, 2, 2]
heapq.heappop(heap)
[inf, 4, 4]
回答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]
来源:https://stackoverflow.com/questions/36876645/unusual-result-from-heappop