python - Python的heapq库管理的项目的顺序是如何确定的?

标签 python python-2.7 heap

我的印象是第一个值决定了堆中的值位置,但事实似乎并非如此。

from __future__ import print_function
import heapq

q = []
heapq.heappush(q, (10, 11))
heapq.heappush(q, (11, 12))
heapq.heappush(q, (9, 10))
print(q)

这给了我一个输出

[(9, 10), (11, 12), (10, 11)]

但是我期待这样的输出

[(9, 10), (10, 11), (11, 12)]

最佳答案

heapq 的条件不是对所提供列表的“排序保证”。相反,它保证 q[k] <= q[2*k+1]q[k] <= q[2*k+2] (在您的示例中使用 q )。

这是因为它在内部作为二叉树进行管理。

如果您只是希望使用排序列表,则可以使用 heappopshown here 。在您的具体示例中,您可以:

sorted_q = [heappop(q) for i in range(len(q))

结果如您所料,将是:

>>> print sorted_q
[(9, 10), (10, 11), (11, 12)]
<小时/>

理论解释here in the docs 。相关的是以下行:

The interesting property of a heap is that a[0] is always its smallest element.

这是条件 q[k] <= q[2*k+1] 的直接结果和q[k] <= q[2*k+2] ,这是堆的一个条件。

但是,对于数组其余部分的顺序没有进一步的保证。事实上,以下两棵树都是有效的堆:

    0
 1     2
2 5   3 4

    0
 2     1
5 3   4 2

分别存储为

[0, 1, 2, 2, 5, 3, 4]

[0, 2, 1, 5, 3, 4, 2]

关于python - Python的heapq库管理的项目的顺序是如何确定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36479149/

相关文章:

python - 数据类型、数据形状和 pad_sequences

python - 使用 python 请求的多部分 POST

python - 在 python 上将用户生成的输入添加到 HTML 文件中

python - 是否可以为数字制作包装对象,例如 float ,使其可变?

Python 请求 : how do I check if a user already logged in or not?

python - 使用Python为excel文件设置密码

algorithm - 寻找第k小的元素数据结构

python - 将 numpy 数组添加到堆队列

Java:有没有办法使用 PriorityQueue 从 O(n) 的数组构造最大堆?

python - 使用套接字创建原始 HTTP 请求