heapq源码解读(一)

Python heapq源码解读计划(一)

本文是解读heapq源码的初始章节,主要目的是介绍heapq这个库的基本使用方法。

heapq的介绍与基本操作

(原文地址:https://docs.python.org/3/library/heapq.html#basic-examples)
这个库提供一个堆的算法实现,也称为优先队列算法。

什么是堆

(这里使用的堆都是小根堆,也成为小顶堆)堆是二叉树,其每个父节点的值都小于或等于其任何子节点。为了方便比较,不存在的元素
都默认是无限大的。

API与教科书的差别
  1. 使用从0开始的索引。这样会使节点的索引和其子节点的索引之间的关系稍微不那么明显,但更合适,因为python是用的从0开始的索引。
  2. 这个库使用的是小根堆而不是大根堆。
初始化

使用一个空列表来创建一个堆,或是使用heapify()来将一个非空列表转换为堆。

heappush(heap,item)

heapq.heappush可以将值添加到heap中去。

Example:

import heapq

array = [1,3,5,2,4]
heap = []
for num in array:
    heapq.heappush(heap,num)


print("array:", array)
print("heap: ", heap)

输出的结果

array: [1, 3, 5, 2, 4]
heap:  [1, 2, 5, 3, 4]

heappop(heap)

将堆顶元素删除,如果堆为空,则会引发IndexError。返回删除的值。

Example:

x = heapq.heappop(heap)
print("heap:",heap)
print("x:",x)

Result:

heap: [2, 3, 5, 4]
x: 1

heappushpop(heap,item)

这是一套组合拳,将item添加到heap中去,然后将堆顶的元素删除,并返回这个被删除的值。

Example:

x = heapq.heappushpop(heap,6)
print("heap:",heap)
print("x:",x)

Result:

heap: [2, 3, 5, 6, 4]
x: 1

heapify(list):

在线性时间内将列表转换成堆。

Example:

heapq.heapify(array)
print("array:", array)

Result:

array: [1, 2, 5, 3, 4]

heapreplace(heap,item)

删除掉堆顶的元素,然后将新元素添加到堆中去。如果堆是空的,则会引发IndexError。

Example:

x = heapq.heapreplace(heap,7)
print("heap:",heap)
print("x:",x)

empty = []
heapq.heapify(empty)
heapq.heappushpop(empty,1)
print("empty: ",empty)
heapq.heapreplace(empty,1)
print("empty:",empty)

Result:

heap: [3, 4, 5, 6, 7]
x: 2
empty:  []
Traceback (most recent call last):
  File "D:/Github/刷题心得/刷题心得指南/Source Code Project/heapq/heapqTest.py", line 25, in <module>
    heapq.heapreplace(empty,1)
IndexError: index out of range

nlargest(n,iterable,key=None)

返回数据集中最大的n个元素组成的列表。

Example:

print("nlargest:",heapq.nlargest(3,heap))

Result:

nlargest: [5, 4, 3]

nsmallest(n,iterable,key=None)

返回数据集中最大的n个元素组成的列表。

Example:

print("nsmallest:",heapq.nsmallest(3,heap))

Result;

nsmallest: [1, 2, 3]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萌小奇0639

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值