heapq 建立小顶堆

参考:https://zhongqiang.blog.csdn.net/article/details/115319669

Python的heapq模块默认建立小顶堆

1. 建堆

两种方式: 一种是使用空列表,然后 heapq.heappush() 函数把值加入,另外一种是 heap.heapify(list) 转换列表成堆

import heapq    # 小顶堆

nums = [2, 3, 5, 1, 54, 23, 132]

# 第一种方式
heap = []
for num in nums:
	heapq.heappush(heap, num)

print(nums, '\n', heap)
print([heapq.heappop(heap) for _ in range(len(nums))])
# [2, 3, 5, 1, 54, 23, 132] 
# [1, 2, 5, 3, 54, 23, 132]
# [1, 2, 3, 5, 23, 54, 132]
# 直接打印heap,只会打印出堆的完全二叉树的层次遍历结果
# 调用heapq.heappop() 才可以获得有序结果


# 第二种方式
heapq.heapify(nums)
print(nums)
print([heapq.heappop(nums) for _ in range(len(nums))])
# [1, 2, 5, 3, 54, 23, 132]
# [1, 2, 3, 5, 23, 54, 132]
# 直接打印heap,只会打印出堆的完全二叉树的层次遍历结果
# 调用heapq.heappop() 才可以获得有序结果

2. 访问堆的内容

堆建好之后,可以通过heapq.heappop()函数弹出堆中最小值。

import heapq

nums = [2, 43, 45, 23, 12]
heapq.heapify(nums)

print(heapq.heappop(nums))  # 2

如果需要删除堆中最小元素并加入一个元素,可以使用 heapq.heaprepalce() 函数

import heapq

nums = [1, 2, 4, 5, 3]
heapq.heapify(nums)

heapq.heapreplace(nums, 23)

print([heapq.heappop(nums) for _ in range(len(nums))])
# out: [2, 3, 4, 5, 23]

如果获取前k 个最大或者最小值, 则可以使用 heapq.nlargest()heapq.nsmallest() 函数

import heapq

nums = [1, 3, 4, 5, 2] 
print(heapq.nlargest(3, nums))    # [5, 4, 3]
print(heapq.nsmallest(3, nums))   # [1, 2, 3]

3. 大顶堆

堆的值可以是元组类型, 可以实现对带权值的元素进行排序
https://www.cnblogs.com/hsiangyu-meng/p/16099524.html
借助此,可以构造大顶堆

from heapq import *

def MaxHeap(nums, key=lambda x: -x):
    maxHeap1 = []
    for i in range(len(nums)):
        heappush(maxHeap1, (-nums[i], nums[i])) # 大顶堆
        # heappush(maxHeap1, nums[i])  # 默认小顶堆
    return heappop(maxHeap1)

# for test
nums = [3, 2, 4, 9]
print(MaxHeap(nums))  # (-9, 9) 最大值是元组的第二个元素 9

4. 合并两个有序列表

合并两个有序列表 heapq.merge(*iterables) 方法
这个方法用于合并多个排序后的序列成一个排序后的序列,返回排序后的值的迭代器

import heapq

nums1 = [32, 3, 5, 34, 54, 23, 132]
nums2 = [23, 2, 12, 656, 324, 23, 54]

nums1.sort()
nums2.sort()

res = heapq.merge(num1, num2)	# 迭代器
print(list(res))
posted @ 2022-05-11 19:28  麦克斯的园丁  阅读(190)  评论(0编辑  收藏  举报