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的数据模型 创建一个文章类 所有开发都是数据 ...
随机推荐
- android Gallery滑动不流畅的解决
import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; impo ...
- crm查询记录共享给了哪些人
有时候,我们须要查询一个记录.共享给了哪些人?怎么做? 第一种做法:是sql的方式 select * from PrincipalObjectAccess where objectid = '5226 ...
- hdu 1421 搬寝室 (dp)
思路分析: dp[i][j] 表示选取到第 i 个 组成了 j 对的最优答案. 当然排序之后 选取相邻两个是更优的. if(i==j*2) dp[i][j] = dp[i-2][j-1] + w[ ...
- InsertOnSubmit、InsertAllOnSubmit等区别 (转)
a. InsertOnSubmit: 将一个实体添加到datacontext对象中,并在SubmitChange()的时候执行更改. b. InsertAllOnSubmit:将一个实体集合添加到da ...
- POJ 2250(最长公共子序列 变形)
Description In a few months the European Currency Union will become a reality. However, to join the ...
- ajax表单提交全路径
//ajax提交form表单的方式 $(document).ready(function() { $('#shopping-submit').click(function() { alert(&quo ...
- Android程序检测网络是否可用
在做Android应用程序中,连接网络的时候,常常要用到检测网络状态是否可用,在这里分享一个比较好用的方法. 本人参考:http://blog.csdn.net/sunboy_2050/article ...
- LeetCode77:Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 - n. For example, ...
- 报错消息写在AT SELECTION-SCREEN OUTPUT和START-OF-SELECTION事件下的区别
今天面试没答上来的问题,其实我是知道的,以前也遇到过.... START-OF-SELECTION下的话会在左下角报错 AT SELECTION-SCREEN OUTPUT消息会弹出框,然后点击就没有 ...
- WinExec函数,启动其他应用程序
WinExec The WinExec function runs the specified application. Note This function is provided only fo ...
