python之堆heapq模块
python之堆heapq模块
堆是一种特殊的树形结构,通常我们所说的堆的数据结构指的是完全二叉树,并且根节点的值小于等于该节点所有子节点的值。
堆是非线性的树形的数据结构,有两种堆,最大堆与最小堆。( heapq库中的堆默认是最小堆)
- 最大堆,树种各个父节点的值总是大于或等于任何一个子节点的值。
- 最小堆,树种各个父节点的值总是小于或等于任何一个子节点的值。
我们一般使用二叉堆来实现优先级队列,它的内部调整算法复杂度为logN。
堆是一个二叉树,其中最小堆每个父节点的值都小于或等于其所有子节点的值。
整个最小堆的最小元素总是位于二叉树的根节点。
常用方法
heappush(heap,item) | 往堆中插入一条新的值 |
heappop(heap) | 从堆中弹出最小值 |
heapreplace(heap,item) | 从堆中弹出最小值,并往堆中插入item 【注意:与heappushpop(heap,item)的区别在于,顺序不同,这里是先进行删除,后压入堆】 |
heappushpop(heap,item) | Python3中的heappushpop更高级 【注意:相当于先操作了heappush(heap,item),然后操作heappop(heap)】 |
heapify(x) | 以线性时间将一个列表转化为堆 【直接会对列表进行排序变成堆排序】 |
merge(*iterables,key=None,reverse=False) | 合并对个堆,然后输出 |
nlargest(n,iterable,key=None) | 返回可枚举对象中的n个最大值并返回一个结果集list |
nsmallest(n,iterable,key=None) | 返回可枚举对象中的n个最小值并返回一个结果集list |
常用方法示例:
import heapq
import randomdef test():li = list(random.sample(range(100), 6))print(li)n = len(li)# nlargestprint("nlargest:", heapq.nlargest(n, li))# nsmallestprint("nsmallest:", heapq.nsmallest(n, li))# heapifyprint('original list is', li)heapq.heapify(li)print('heapify list is', li)# heappush & heappop heapq.heappush(li, 105)print('pushed heap is', li)heapq.heappop(li)print('popped heap is', li)# heappushpop & heapreplace heapq.heappushpop(li, 130) # heappush -> heappopprint('heappushpop', li)heapq.heapreplace(li, 2) # heappop -> heappushprint('heapreplace', li)test()
运行结果:
堆排序示例
heapq模块中有几张方法进行排序:
方法一:
import heapqdef heap_sort(iterable):heap = []for i in iterable:heapq.heappush(heap, i)return [heapq.heappop(heap) for _ in range(len(heap))]if __name__ == '__main__':li = [30, 40, 60, 10, 20, 50]print(heap_sort(li))
运行结果:
方法二(使用nlargest或nsmallest):
import heapqli = [30, 40, 60, 10, 20, 50]
# nlargest
n = len(li)
print("nlargest:", heapq.nlargest(n, li))
# nsmallest
print("nsmallest:", heapq.nsmallest(n, li))
运行结果:
方法三(使用heapify):
import heapqdef heap_sort(list):print(list)heapq.heapify(list)print(list)heap = []while (list):heap.append(heapq.heappop(list))print(heap)li[:] = heapprint(li)if __name__ == '__main__':li = [30, 40, 60, 10, 20, 50]heap_sort(li)
运行结果:
堆在优先级队列中的应用
需求:实现任务的添加,删除(相当于任务的执行),修改任务优先级
from heapq import *
import itertoolspq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = '<removed-task>' # placeholder for a removed task
counter = itertools.count() # unique sequence countdef add_task(task, priority=0):'Add a new task or update the priority of an existing task'if task in entry_finder:remove_task(task)count = next(counter)entry = [priority, count, task]entry_finder[task] = entryheappush(pq, entry)def remove_task(task):'Mark an existing task as REMOVED. Raise KeyError if not found.'entry = entry_finder.pop(task)entry[-1] = REMOVEDdef pop_task():'Remove and return the lowest priority task. Raise KeyError if empty.'while pq:priority, count, task = heappop(pq)if task is not REMOVED:del entry_finder[task]return taskraise KeyError('pop from an empty priority queue')
python之堆heapq模块相关推荐
- python基础之heapq模块(堆模块)
堆是一种数据结构,本质上是一种二叉树.在python中可以使用heapq模块实现,heapq可以实现一个简单的优先级队列. 一.堆的性质 堆分为小根堆与大根堆,小根堆的第一个元素可以理解为数值最小的元 ...
- [转载] python中 堆heapq以及 队列queue的使用
参考链接: Python中的堆队列(Heap queue或heapq) python中 堆heapq以及 队列queue的使用 1. 堆heapq的使用 ## -------------------- ...
- python collection 和 heapq 模块使用说明
一 :集合库collection python 拥有一些内置的数据类型,collections模块提供啦几个额外的数据类型: 1,namedtuple 生成可以使用名字来访问元素内容的tuple子 ...
- python设置堆大小_Python中的堆问题
Heap in python 堆(英语:Heap)是计算机科学中一类特殊的数据结构的统称.堆通常是一个可以被看做一棵树的数组对象.在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时 ...
- Python中的堆实现:heapq 模块——利用堆结构实现快速访问数据流中的中位数
堆结构 堆结构是一种优先队列,可以以任意顺序添加对象,并随时查找或删除最小(大)的元素,或者查找和删除前 K 个最小(大)元素.相比于列表方法min() / max(),这样做的效率要高得多. 堆结构 ...
- python树状节点 可拖拽_Python 的 heapq 模块源码分析
原文链接:Python 的 heapq 模块源码分析 起步 heapq 模块实现了适用于Python列表的最小堆排序算法. 堆是一个树状的数据结构,其中的子节点都与父母排序顺序关系.因为堆排序中的树是 ...
- Python 的 heapq 模块源码分析
作者:weapon 来源:https://zhuanlan.zhihu.com/p/54260935 起步 heapq 模块实现了适用于Python列表的最小堆排序算法. 堆是一个树状的数据结构,其中 ...
- python分配 使最大的最小_python3中的heapq模块使用
###heapq-堆排序算法 heapq实现了一个适合与Python的列表一起使用的最小堆排序算法. 二叉树 树中每个节点至多有两个子节点 满二叉树 树中除了叶子节点,每个节点都有两个子节点 什么是完 ...
- Python heapq模块
Python heapq模块 heapq模块提供了如下几个函数: 函数 用法 heapq.heappush(heap, item) 把item添加到heap中(heap是一个列表) heapq.hea ...
最新文章
- 如皋技校计算机老师,如皋中专计算机考试名列南通第一 共2457人参考合格率达95.5%...
- Typescript + TSLint + webpack 搭建 Typescript 的开发环境
- 电路常识性概念(5)-上拉电阻、下拉电阻 / 拉电流、灌电流 / 扇出系数
- java 6大原则_java 6大设计原则 一:观察者模式
- 【计算机科学基础】电子计算机抽象层次
- WPF中制作立体效果的文字或LOGO图形
- 启动和停止一个服务,修改服务的启动类型 Start and Stop Service for windows
- 摄影专业学生,没有摄影棚,怎么练摄影?
- js web端扫码枪对接
- 别做正常的傻瓜-读后感
- rsync和inotify远程同步
- 线性代数之特征值与特征向量的求法
- 谷歌浏览器安装vue-devtools插件
- 3.3KW车载充电机开关电源设计方案资料数字控制单相PFC与全桥LLC 3.3KW 车载充电机OBC
- 跪了!美团Android开发工程师岗位职能要求,重难点整理
- 计算一幅图像的平均亮度
- 【opencv】在图片上画角并且进行角度检测
- App2sd功能和Asec文件
- 近期风靡互联网的Deep Dream人工智能图像识别软件
- C++ 代码模拟登录淘宝、天猫、支付宝等电商网站的实现
热门文章
- 基于 Python 的 8 种常用抽样方法
- 中国安全态势越来越好,专访山石网科CSO蒋东毅 | 拟合
- @所有人,CSDN 粉丝专属福利来啦!
- 华为于璠:新一代AI开源计算框架MindSpore的前世与今生 | AI ProCon 2019
- 渗透各行各业,这家RPA外企宣布全面进军中国市场
- 只讲技术,拒绝空谈!2018 AI开发者大会精彩议程曝光
- 入华十年,一家互联网外企的“另类”视频广告模式
- Google母公司5600万美元首投AI芯片初创公司,看上了SambaNova的什么?
- 动态代理竟然如此简单!
- Thread.sleep(0) 有什么用?