Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET
Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET
import heapq
help(heapq)
heapq 是一个最小堆,堆顶元素 a[0] 永远是最小的. 和 Java 中的优先队列类似.
-------------------------------------------------
Help on module heapq:
NAME
heapq - Heap queue algorithm (a.k.a. priority queue).FILE
/usr/lib64/python2.4/heapq.pyDESCRIPTION
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0. For the sake of comparison,
non-existing elements are considered to be infinite. The interesting
property of a heap is that a[0] is always its smallest element.
Usage:
heap = [] # creates an empty heap
heappush(heap, item) # pushes a new item on the heap
item = heappop(heap) # pops the smallest item from the heap
item = heap[0] # smallest item on the heap without popping it
heapify(x) # transforms list into a heap, in-place, in linear time
item = heapreplace(heap, item) # pops and returns smallest item, and adds
# new item; the heap size is unchanged
Our API differs from textbook heap algorithms as follows:
- We use 0-based indexing. This makes the relationship between the
index for a node and the indexes for its children slightly less
obvious, but is more suitable since Python uses 0-based indexing.
- Our heappop() method returns the smallest item, not the largest.
These two make it possible to view the heap as a regular Python list
without surprises: heap[0] is the smallest item, and heap.sort()
maintains the heap invariant!FUNCTIONS
heapify(...)
Transform list into a heap, in-place, in O(len(heap)) time.
heappop(...)
Pop the smallest item off the heap, maintaining the heap invariant.
heappush(...)
Push item onto heap, maintaining the heap invariant.
heapreplace(...)
Pop and return the current smallest value, and add the new item.
This is more efficient than heappop() followed by heappush(), and can be
more appropriate when using a fixed-size heap. Note that the value
returned may be larger than item! That constrains reasonable uses of
this routine unless written as part of a conditional replacement:
if item > heap[0]:
item = heapreplace(heap, item)
nlargest(...)
Find the n largest elements in a dataset.
Equivalent to: sorted(iterable, reverse=True)[:n]
nsmallest(...)
Find the n smallest elements in a dataset.
Equivalent to: sorted(iterable)[:n]
构建元素个数为 K=5 的最小堆代码实例:
- #!/usr/bin/env python
- # -*- encoding: utf-8 -*-
- # Author: kentzhan
- #
- import heapq
- import random
- heap = []
- heapq.heapify(heap)
- for i in range(15):
- item = random.randint(10, 100)
- print "comeing ", item,
- if len(heap) >= 5:
- top_item = heap[0] # smallest in heap
- if top_item < item: # min heap
- top_item = heapq.heappop(heap)
- print "pop", top_item,
- heapq.heappush(heap, item)
- print "push", item,
- else:
- heapq.heappush(heap, item)
- print "push", item,
- pass
- print heap
- pass
- print heap
- print "sort"
- heap.sort()
- print heap
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author: kentzhan
# import heapq
import random heap = []
heapq.heapify(heap)
for i in range(15):
item = random.randint(10, 100)
print "comeing ", item,
if len(heap) >= 5:
top_item = heap[0] # smallest in heap
if top_item < item: # min heap
top_item = heapq.heappop(heap)
print "pop", top_item,
heapq.heappush(heap, item)
print "push", item,
else:
heapq.heappush(heap, item)
print "push", item,
pass
print heap
pass
print heap print "sort"
heap.sort() print heap结果:
Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET的更多相关文章
- 解决基于BAE python+bottle开发上的一系列问题 - artwebs - 博客频道 - CSDN.NET
解决基于BAE python+bottle开发上的一系列问题 - artwebs - 博客频道 - CSDN.NET 解决基于BAE python+bottle开发上的一系列问题 分类: python ...
- python实现的文本编辑器 - Skycrab - 博客频道 - CSDN.NET
Download Qt, the cross-platform application framework | Qt Project Qt 5.2.1 for Windows 64-bit (VS 2 ...
- python random模块 - 小驹的专栏 - 博客频道 - CSDN.NET
python random模块 - 小驹的专栏 - 博客频道 - CSDN.NET python random模块 分类: python 2011-11-15 15:31 6037人阅读 评论(2) ...
- 堆数据结构(heapq)简单应用
## 堆数据结构(heapq)简单应用 # 堆数据结构 heapq # 常用方法:nlargest(),nsmallest(),heapify(),heappop() # 如果需要的个数较小,使用nl ...
- Python 爬取CSDN博客频道
初次接触python,写的很简单,开发工具PyCharm,python 3.4很方便 python 部分模块安装时需要其他的附属模块之类的,可以先 pip install wheel 然后可以直接下载 ...
- python实现自动发送微博,当自己写博客时同步上去。
一.需求: 自己在github上搭建一个基于Jekyll的博客(http://beginman.cn/),每次写完博客后就要push上去,博客写的再好,基本上没人访问,为了增加访问量,就想利用起来微博 ...
- Python爬虫学习之正则表达式爬取个人博客
实例需求:运用python语言爬取http://www.eastmountyxz.com/个人博客的基本信息,包括网页标题,网页所有图片的url,网页文章的url.标题以及摘要. 实例环境:pytho ...
- python有哪些好的学习资料或者博客?
推荐Full Stack Python 有各种python资源汇总,从基础入门到各种框架web应用开发和部署,再到高级的ORM.Docker都有.以下是Full Stack Python 上总结的一些 ...
- Python Web开发:Django+BootStrap实现简单的博客项目
创建blog的项目结构 关于如何创建一个Django项目,请查看[Python Web开发:使用Django框架创建HolleWorld项目] 创建blog的数据模型 创建一个文章类 所有开发都是数据 ...
随机推荐
- Ubuntu下ssh免password登录安装
1.首先在本机安装openssh-server和openssh-client. 命令:sudo apt-get install openssh-server openssh-client 2.在检查当 ...
- CentOS: make menuconfig error: curses.h: No such file or directory
the problem when use centos5 to build kernel or busybox step 1. Centos中关于 ncurses.h:no such file or ...
- WCF技术剖析之二十一:WCF基本异常处理模式[中篇]
原文:WCF技术剖析之二十一:WCF基本异常处理模式[中篇] 通过WCF基本的异常处理模式[上篇], 我们知道了:在默认的情况下,服务端在执行某个服务操作时抛出的异常(在这里指非FaultExcept ...
- Hashtable的使用
Hashtable mylist = new Hashtable(); mylist.Add("1", "100"); ...
- CF 224 B Array
给你n个数,求[l, r] 的一段数,a[l] - a[r] 一共含有k个不相同的数,且sum a[l, r] 最小的那一段. 用队列维护当前数段中不同元素的个数即可. #include<ios ...
- Delphi中运行时改变panel的位置及大小(通过wm_SysCommand来实现)
procedure TForm1.pnl1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Int ...
- Linux主机上发布java web应用
1.链接远程主机命令 ssh user@hostname 如: shh root@192.168.1.1 2.查看主机操作系统版本 uname -a 3.linux系统安装mysql a)检查是否安装 ...
- 499 - What's The Frequency, Kenneth?
What's The Frequency, Kenneth? #include <stdio.h> main() { int i; char *suffix[]= { "st ...
- RobotFramework 自定义Library
RobotFramework 主要使用Python,这里简单自定义Library,以扩充RobotFramework的功能 新建一个python类,自定义需要的方法 例如: 保存成TestLibrar ...
- 浅析——SCTP协议(转)
SCTP处于SCTP用户应用层与IP网络层之间,它运用“关联”(association)这个术语定义交换信息的两个对等SCTP用户间的协议状态 .SCTP也是面向连接的,但在概念上,SCTP“关联”比 ...
