python自带小顶堆heapq用法简例

本文介绍了如何在Python中使用heapq模块实现小顶堆,并展示了如何处理包含tuple和list元素,以及numpy数组的heapq操作。包括heapify、heappush和heappop等函数的使用实例以及heapq.merge的错误用法。
摘要由CSDN通过智能技术生成

Python 自带 heapq[1] 模块实现堆(heap),是小顶堆(min heap),元素可以是简单的数据类型(数字、字符串),也可以是 tuple/list,不过要保证同类型,如不能同时出现 tuple 和 list。

当元素是 tuple/list,元素比较就像字典序一样,此时要求每个元素的比较都定义好,不然可能会报错(如 numpy.ndarray 的比较)。

简例:

import pprint, heapq, copy
import numpy as np
# import medpy.io as medio
# from PIL import Image
# import skimage
import heapq

print('\t1, build a heap')
x = [1, 0.2, -3.4, 5., .6, -.7, -8., 9]#, "10"]
heapq.heapify(x)
while len(x) > 0:
    t = heapq.heappop(x)
    print(t)


data = [
    (1.2, 17, 'tom', np.random.randn(3)),
    (1.2, 18, 'jerry', np.random.randn(3)),
    (1.2, 18, 'spike', np.random.randn(3)),
    # (1.2, 18, 'spike', np.random.randn(3)), # error, `<` of numpy.ndarray not well defined
    (1.2, 18, 'spike'), # 短一点
    (3.4, 18, 'Toodles Galore', np.random.randn(3)),
    (5.6, 19, 'tara', np.random.randn(3)),
    # [1.2, 10, 'tuffy', np.random.randn(3)] # error, should be same type
]
data = [list(datum) for datum in data] # OK


print('\t2, build & maintain a heap')
x = []
for datum in data:
    if len(x) > 3:
        t = heapq.heappushpop(x, datum)
        print(t, len(x))
    else:
        heapq.heappush(x, datum)

while len(x) > 0:
    t = heapq.heappop(x)
    print(t, len(x))


print('\t3, heapq.merge 错用')
y, z = [], []
for i in range(len(data) // 2):
    heapq.heappush(y, data[i])
for i in range(len(data) // 2, len(data)):
    heapq.heappush(z, data[i])
# 不能这么  heapq.merge 两个 heap
# 因为 heapq.merge 假设所有要 merge 的序列是 sort 过的
# 而 heap sort 的顺序与 sort 不同!
for t in heapq.merge(y, z):
    print(t)

输出:

        1, build a heap
-8.0
-3.4
-0.7
0.2
0.6
1
5.0
9

        2, build & maintain a heap
[1.2, 17, 'tom', array([-1.21815652,  0.49500269,  0.8530528 ])] 4
[1.2, 18, 'jerry', array([0.25093173, 0.28760793, 0.22501419])] 4
[1.2, 18, 'spike'] 3
[1.2, 18, 'spike', array([0.8459503 , 0.72552735, 0.71327913])] 2
[3.4, 18, 'Toodles Galore', array([0.58576024, 0.3357778 , 1.52392345])] 1
[5.6, 19, 'tara', array([-1.28955814, -2.23286344, -1.25304415])] 0

        3, wrong usage
[1.2, 17, 'tom', array([-1.21815652,  0.49500269,  0.8530528 ])]
[1.2, 18, 'jerry', array([0.25093173, 0.28760793, 0.22501419])]
[1.2, 18, 'spike']
[1.2, 18, 'spike', array([0.8459503 , 0.72552735, 0.71327913])]
[3.4, 18, 'Toodles Galore', array([0.58576024, 0.3357778 , 1.52392345])]
[5.6, 19, 'tara', array([-1.28955814, -2.23286344, -1.25304415])]

References

  1. heapq — Heap queue algorithm
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值