python中heapq的库是什么,如何确定Python的heapq库管理的项目顺序?

I was under the impression that the first value was what determined a values position in the heap, however that doesn't seem to be the case.

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)

This gives me an output of

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

However I was expecting an output like

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

解决方案

The condition on heapq is not a "sort guarantee" over the provided list. Instead, it guarantees q[k] <= q[2*k+1] and q[k] <= q[2*k+2] (using q as in your example).

This is due that it is managed internally as a binary tree.

If you simply expect to use the sorted list, you can use the heappop as shown here. In your specific example you could:

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

and the result, as you expected, will be:

>>> print sorted_q

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

The theory is explained here in the docs. Relevant is the following line:

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

Which is a direct result of the condition q[k] <= q[2*k+1] and q[k] <= q[2*k+2], which is a condition of the heap.

However, there are no further guarantees about the order on the rest of the array. And, in fact, both following trees are valid heaps:

0

1 2

2 5 3 4

and

0

2 1

5 3 4 2

Which are stored, respectively, as

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

and

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值