Python——heap
来源:互联网 发布:淘宝美工详情页模板 编辑:程序博客网 时间:2024/06/06 23:51
通过优先队列可以构造堆,堆是一种实用的数据结构。尽管Python中没有独立的堆类型,但是包含了一些对操作函数的模块,这个模块叫heapq,主要的操作包含如下几个:
heappush(heap,x):x元素插入堆
heappop(heap):弹出对中最小元素
heapify(heap):将heap属性强制应用到任意一个列表
hrapreplace(heap,x):将heap中最小元素弹出,同时x元素入堆
hlargest(n,iter):返回iter中第n大的元素
hsmallest(n,iter):返回iter中第n小的元素
堆的定义和使用如下:
>>> from heapq import *>>> from random import shuffle>>> x=[1,2,3,4,5,6]>>> shuffle(x)>>> heap=[]>>> for i in x: heappush(heap,i)>>> heap[1, 3, 2, 6, 4, 5]>>>
注:shuffle函数将列表顺序打乱
堆元素的追加:
>>> heap[1, 3, 2, 6, 4, 5]>>> heappush(heap,0)>>> heap[0, 3, 1, 6, 4, 5, 2]>>>
删除堆中元素:
>>> heap[0, 3, 1, 6, 4, 5, 2]>>> heappop(heap)0>>> heap[1, 3, 2, 6, 4, 5]>>> heappop(heap)1>>> heap[2, 3, 5, 6, 4]>>>
heapify函数将列表生成堆:
>>> x=[1,4,2,3,5,4]>>> heapify(x)>>> x[1, 3, 2, 4, 5, 4]>>> heappop(x)1>>> heappop(x)2>>> x[3, 4, 4, 5]>>>
hrapreplace函数弹出最小元素将另一个元素加入堆:
>>> x[3, 4, 4, 5]>>> heapreplace(x,0)3>>> x[0, 4, 4, 5]>>>
0 0
- Python——heap
- Python中的堆数据结构——heap模块
- heap——sort
- 堆——heap
- python heap sort
- heap in python
- Python heap - priority queue
- STL——heap堆
- STL——堆heap
- STL——Heap算法
- 【STL】顺序容器 — heap
- 浅谈数据结构—堆(heap)
- Python实现Hash Heap数据结构
- [硕.Love Python] Heap(堆)
- python学习笔记--堆(heap)
- 编程练习——堆heap
- C++ STL——heap相关算法
- STL系列——堆(heap)
- 【USACO2.3.2】奶牛家谱 BSOJ2086 洛谷P1472 CODEVS2053
- Android开发笔记—GridView的基础使用
- Leetcode #42 #407 Solution
- 堆排序算法在Java中的实现
- Java was started but returned exit code=13 问题解决
- Python——heap
- C语言的可变参函数
- osgEarth编译
- ProtoBuf(protocol buffer) 网络传输协议
- 帧同步游戏的设计
- 从NSArray看类簇
- Android关闭所有activity的方法,利用baseActivity
- 加密方式之MD5
- el循环map、list