Unusual result from heappop?

旧街凉风 提交于 2021-02-11 04:58:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!