python学习笔记之heapq内置模块
heapq内置模块位于./Anaconda3/Lib/heapq.py,提供基于堆的优先排序算法
堆的逻辑结构就是完全二叉树,并且二叉树中父节点的值小于等于该节点的所有子节点的值。这种实现可以使用 heap[k] <= heap[2k+1] 并且 heap[k] <= heap[2k+2] (其中 k 为索引,从 0 开始计数)的形式体现,对于堆来说,最小元素即为根元素 heap[0]。
1.初始化
可以通过 list 对 heap 进行初始化,或者通过 api 中的 heapify 将已知的 list 转化为 heap 对象。
2. heapq.py中提供的函数方法
heapq.heappush(heap, item)
heapq.heappop(heap):返回 root 节点,即 heap 中最小的元素。
heapq.heapreplace(heap,item): python3中heappushpop的更高效版。
heapq.heappushpop(heap, item):向 heap 中加入 item 元素,并返回 heap 中最小元素。
heapq.heapify(x):Transform list into a heap, in-place, in O(len(x)) time
heapq.merge(*iterables, key=None, reverse=False)
heapq.nlargest(n, iterable, key=None):返回可枚举对象中的 n 个最大值,并返回一个结果集 list,key 为对该结果集的操作。
heapq.nsmallest(n, iterable, key=None):同上相反
heapq._heappop_max(heap): Maxheap version of a heappop
heapq._heapreplace_max(heap,item):Maxheap version of a heappop followed by a heappush.
heapq._heapify_max(x):Transform list into a maxheap, in-place, in O(len(x)) time
heapq._siftdown(heap,startpos,pos): Follow the path to the root, moving parents down until finding a place
heapq._siftup(heap,pos):Bubble up the smaller child until hitting a leaf
heapq._siftdown_max(heap,startpos,pos):Maxheap variant of _siftdown
heapq._siftup_max(heap,pos):Maxheap variant of _siftup
3. 举例
import heapq
def heapsort(iterable):
h = []
for i in iterable:
heapq.heappush(h, i)
return [heapq.heappop(h) for i in range(len(h))] # method 1: sort to list
s = [3, 5, 1, 2, 4, 6, 0, 1]
print(heapsort(s))
'''
[0, 1, 1, 2, 3, 4, 5, 6]
''' # method 2: use key to find price_min
portfolio = [{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}]
cheap = heapq.nsmallest(1, portfolio, key=lambda s:s['price'])
print(cheap)
'''
[{'name': 'YHOO', 'shares': 45, 'price': 16.35}]
''' # method 3: use while to push min element
def heapilize_list(x):
n = len(x)
# 获取存在子节点的节点 index 列表,并对每个节点单元进行最小堆处理
for i in reversed(range(n // 2)):
raiseup_node(x, i) def put_down_node(heap, startpos, pos):
current_item = heap[pos]
# 判断单元中最小子节点与父节点的大小
while pos > startpos:
parent_pos = (pos - 1) >> 1
parent_item = heap[parent_pos]
if current_item < parent_item:
heap[pos] = parent_item
pos = parent_pos
continue
break
heap[pos] = current_item def raiseup_node(heap, pos):
heap_len = len(heap)
start_pos = pos
current_item = heap[pos]
left_child_pos = pos * 2 + 1
while left_child_pos < heap_len:
right_child_pos = left_child_pos + 1
# 将这个单元中的最小子节点元素与父节点元素进行位置调换
if right_child_pos < heap_len and not heap[left_child_pos] < heap[right_child_pos]:
left_child_pos = right_child_pos
heap[pos] = heap[left_child_pos]
pos = left_child_pos
left_child_pos = pos * 2 + 1
heap[pos] = current_item
put_down_node(heap, start_pos, pos) p = [4, 6, 2, 10, 1]
heapilize_list(p)
print(p)
'''
[1, 4, 2, 10, 6]
'''
python学习笔记之heapq内置模块的更多相关文章
- python学习笔记整理——字典
python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...
- VS2013中Python学习笔记[Django Web的第一个网页]
前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...
- python学习笔记之module && package
个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...
- python学习笔记(六)文件夹遍历,异常处理
python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...
- python学习笔记--Django入门四 管理站点--二
接上一节 python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...
- python学习笔记--Django入门0 安装dangjo
经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...
- python学习笔记(一)元组,序列,字典
python学习笔记(一)元组,序列,字典
- Pythoner | 你像从前一样的Python学习笔记
Pythoner | 你像从前一样的Python学习笔记 Pythoner
- OpenCV之Python学习笔记
OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...
随机推荐
- JAVA基础篇—HashMap
/class Depositor package 银行储户; public class Depositor { private String id; private String name; priv ...
- LeetCode(23)Merge k Sorted Lists
题目 Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity ...
- Java策略模式(Strategy)
一.定义 定义一组算法,将每个算法都封装起来,并且使它们之间可以互换.策略模式使这些算法在客户端调用它们的时候能够互不影响地变化.(Java的TreeSet集合中,构造方法可传入具体的比较器对象以实现 ...
- AD转换器的参数介绍
分辨率.参考电压这些地球人都知道的就不说了. 当“参考电压”和“分辨率”被确定后,每两个数值间的差值,即“步进量”. 上面的“步进量”在AD中称为1LSB(最低有效位,Least Significan ...
- HDU4010 Query on The Trees (LCT动态树)
Query on The Trees Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Othe ...
- 《小团团团队》【Alpha】Scrum Meeting 3
项目 内容 课程名 软件工程 作业链接地址 Github地址 团队名称 小团团团队 具体目标 1.掌握软件测试基础技术:2.学习迭代式增量软件开发过程(Scrum) 1.1前言 第三天 时间: 201 ...
- 【Shell】使用shell打印菜单,一键安装Web应用
问题描述: [解答] [root@A04-Test- scripts]# more menu.sh #!/bin/bash echo "1.[install lamp]" echo ...
- Struts2理解——转发和重定向
转发和重定向设置: <action name="deptAction" class="com.syaccp.erp.action.DeptA ...
- LibreOJ2085 - 「NOI2016」循环之美
Portal Description 给出\(n,m(n,m\leq10^9)\)和\(k(k\leq2000)\),求在\(k\)进制下,有多少个数值不同的纯循环小数可以表示成\(\dfrac{x} ...
- Unity Microphone 录音时 检测声音大小
刚开始以为只取录音时的最后一个sample来判断音量大小,发现都检测不到. 后来搜索了一下,原来需要取一段sample来判断,有的是这一段取平均值作为音量大小.我这里是取出一段sample中的峰值(p ...