python自带小顶堆heapq用法简例

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

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
Python中,实现小顶堆某个元素出可以使用`heapq`库,也可以手动实现小顶堆类来完成。 ### 使用`heapq`库 `heapq`库默认实现的是小顶堆,其`heappop`方法可以实现元素出,即提取中的最小值。示代码如下: ```python import heapq # 初始化一个列表 arr = [18, 34, 26, 25, 30, 8, 28, 13] # 将列表转换为小顶堆 heapq.heapify(arr) # 出操作,提取中的最小值 min_value = heapq.heappop(arr) print("出的最小值:", min_value) print("剩余中的元素:", arr) ``` ### 手动实现小顶堆类 手动实现小顶堆类时,`extract_min`方法可以实现元素出。以下是一个单的小顶堆类实现: ```python class MinHeap: def __init__(self): self.heap = [] def insert(self, value): self.heap.append(value) self._sift_up(len(self.heap) - 1) def extract_min(self): if len(self.heap) == 0: return None if len(self.heap) == 1: return self.heap.pop() min_value = self.heap[0] self.heap[0] = self.heap.pop() self._sift_down(0) return min_value def _sift_up(self, index): parent_index = (index - 1) // 2 while index > 0 and self.heap[index] < self.heap[parent_index]: self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index] index = parent_index parent_index = (index - 1) // 2 def _sift_down(self, index): left_child_index = 2 * index + 1 right_child_index = 2 * index + 2 smallest = index if left_child_index < len(self.heap) and self.heap[left_child_index] < self.heap[smallest]: smallest = left_child_index if right_child_index < len(self.heap) and self.heap[right_child_index] < self.heap[smallest]: smallest = right_child_index if smallest != index: self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index] self._sift_down(smallest) # 使用示 heap = MinHeap() values = [18, 34, 26, 25, 30, 8, 28, 13] for value in values: heap.insert(value) min_value = heap.extract_min() print("出的最小值:", min_value) ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值