栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

heapq源码解读(一)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 
    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]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650230.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号