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做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...
随机推荐
- freertos知识点笔记——队列、二值信号量、计数信号量
队列1.队列queue通常用于任务之间的通信,一个任务写缓存,另一个任务读缓存.队列还会有等待时间,2.阻塞超时时间.如果在发送时队列已满,这个时间即是任务处于阻塞态等待队列空间有效的最长等待时间.如 ...
- The 2018 ACM-ICPC Chinese Collegiate Programming Contest Maximum Element In A Stack
//利用二维数组模拟 #include <iostream> #include <cstdio> #include <cstring> #include <s ...
- Linux学习-善用判断式
利用 test 指令的测试功能 要检测系统上面某些文件或者是相关的属性时,利用 test 这个指令来工作真是好用得不 得了, 举例来说,我要检查 /dmtsai 是否存在时,使用: [dmtsai@s ...
- #1 add life to static pages && connect to MySQL
由于实验室 Project 中需要用到PHP, 之前也没接触过 PHP, 因此把 编程入门 <Head Fist PHP & MySQL >找来花了四五天快速过了一遍. 现在想把书 ...
- python-网络编程-02
[1] server端 首先我们看下一个最简单http服务端 import socket def handle_request(client): buf = client.recv(1024) cli ...
- 顺序表ans链性表
#include<stdio.h>#include<malloc.h>#include<string.h>typedef int ElemType;typedef ...
- C++大数相加
c++ string sum(string s1,string s2) { if(s1.length()<s2.length()) { string temp=s1; s1=s2; s2=tem ...
- Golang指针
学过C语言的老司机都知道,指针就是一个变量,用于存储另一个变量的内存地址. 那么什么是变量呢?在现代计算机体系结构中所有的需要执行的信息代码都需要存储在内存中,为了管理存储在内存的数据,内存是划分为不 ...
- [HAOI2007] 理想的正方形 (单调队列)
题目链接 Solution MD,经过这道题,算是掌握单调队列了... 可以先预处理出点 \((i,j)\) 往上 \(n\) 的最大值和最小值. 然后再横着做一遍单调队列即可. Code #incl ...
- P3285 松鼠的新家 (树链剖分)
题目描述 松鼠的新家是一棵树,前几天刚刚装修了新家,新家有n个房间,并且有n-1根树枝连接,每个房间都可以相互到达,且俩个房间之间的路线都是唯一的.天哪,他居然真的住在”树“上. 松鼠想邀请小熊维尼前 ...