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学习笔记之heapq内置模块的更多相关文章

  1. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

  2. VS2013中Python学习笔记[Django Web的第一个网页]

    前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...

  3. python学习笔记之module && package

    个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...

  4. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  5. python学习笔记--Django入门四 管理站点--二

    接上一节  python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...

  6. python学习笔记--Django入门0 安装dangjo

    经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...

  7. python学习笔记(一)元组,序列,字典

    python学习笔记(一)元组,序列,字典

  8. Pythoner | 你像从前一样的Python学习笔记

    Pythoner | 你像从前一样的Python学习笔记 Pythoner

  9. OpenCV之Python学习笔记

    OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...

随机推荐

  1. 在spring boot中使用webSocket组件(二)

    该篇演示如何使用websocket创建一对一的聊天室,废话不多说,我们马上开始! 一.首先先创建前端页面,代码如下图所示: 1.login.html <!DOCTYPE html> < ...

  2. HDU 5536 Chip Factory Trie

    题意: 给出\(n(3 \leq n \leq 1000)\)个数字,求\(max(s_i+s_j) \bigoplus s_k\),而且\(i,j,k\)互不相等. 分析: 把每个数字看成一个\(0 ...

  3. iOS启动图 LaunchImage LaunchScreen.xib

    1.Images.xcassets添加LaunchImage 2.具体大小和添加类别都是可以调的 640*960   (4/4s)                                 2X ...

  4. python中json操作了解

    什么是接口? 交换数据 http://openweathermap.org/current json简介 JSON 是存储和交换文本信息的语法.类似 XML JSON 语法是 JavaScript 语 ...

  5. day05_05 for循环、break语句

    1.0 输入用户名,密码练习 _user = "alex" _passwd = "abc123" username = input("Username ...

  6. javascript是脚本语言?javascript万物皆对象?

    呵呵哒!带你见识下js面对对象的魅力 是的是的,退后,朕要开始装逼了- 这是什么鸟东西?是的是的,装逼开始,2016年度最佳JS编译器,ES6标准出来后,小伙伴们对新特性摩拳擦掌,奈何浏览器支持把我们 ...

  7. POJ 2181 Jumping Cows

    Jumping Cows Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 6398   Accepted: 3828 Desc ...

  8. Linux Shell系列教程之(三)Shell变量

    本文是Linux Shell系列教程的第(三)篇,更多shell教程请看:Linux Shell系列教程 Shell作为一种高级的脚本类语言,也是支持自定义变量的.今天就为大家介绍下Shell中的变量 ...

  9. 二进制<1>

    Matrix67:位运算简介及实用技巧(一) 基础篇 什么是位运算?    程序中的所有数在计算机内存中都是以二进制的形式储存的.位运算说穿了,就是直接对整数在内存中的二进制位进行操作.比如,and运 ...

  10. Java面试题之谈谈reactor模型

    reactor是什么? 事件驱动 可以处理一个或多个输入源 通过Service Handle同步的将输入事件采用多路复用分发给相应的Request Handler(一个或多个)处理 具体可参考:htt ...