PyMOTW: heapq — PyMOTW Document v1.6 documentation

PyMOTW: heapq

  • 模块: heapq
  • 目的: 就地堆排序算法
  • python版本:New in 2.3 with additions in 2.5 2.3+, 2.5中有所增加

heapq实现了适用于Python列表的小顶堆排序算法.

描述

堆是一种树型数据结构, 其父子节点间具有顺序关系. 二进制堆可以使用一个列表或数组来表示, 其中元素N的孩子所在位置为2*N+1 和 2*N+2(以0开始计算位置). 这种特征让就地重排成为可能, 这样在增加或删除元素时就不需要重新分配内存空间.

大顶堆确保每个父元素都大于或等于他的任一个孩子元素. 而小顶堆则需要每个父元素都要小于或等于他的任一个孩子元素. Python的heapq模块实现的是小顶堆.

示例数据

本文的例子中使用的是如下的示例数据:

data = [19, 9, 4, 10, 11, 8, 2]

创建一个堆

有两个基本的堆创建方式, 分别是heappush()和heapify().

使用heappush(), 堆中元素排序顺序是随着新元素的不断增加而不断更新的.

import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data heap = []
print 'random :', data
print for n in data:
print 'add %3d:' % n
heapq.heappush(heap, n)
show_tree(heap)
$ python heapq_heappush.py
random : [19, 9, 4, 10, 11, 8, 2] add 19: 19
------------------------------------ add 9: 9
19
------------------------------------ add 4: 4
19 9
------------------------------------ add 10:
4
10 9
19
------------------------------------ add 11: 4
10 9
19 11
------------------------------------ add 8: 4
10 8
19 11 9
------------------------------------ add 2: 2
10 4
19 11 9 8
------------------------------------

如果数据已经在内存中了, 使用heapify()进行就地排序会更有效.

import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data print 'random :', data
heapq.heapify(data)
print 'heapified :'
show_tree(data)
$ python heapq_heapify.py
random : [19, 9, 4, 10, 11, 8, 2]
heapified : 2
9 4
10 11 8 19
------------------------------------

访问堆

成功建立堆之后, 可以使用heappop()删除堆中最小的元素. 下面的例子改编自标准库文档中的例子, heapify()和heappop()用于对一个列表进行排序.

import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data print 'random :', data
heapq.heapify(data)
print 'heapified :'
show_tree(data)
print inorder = []
while data:
smallest = heapq.heappop(data)
print 'pop %3d:' % smallest
show_tree(data)
inorder.append(smallest)
print 'inorder :', inorder
$ python heapq_heappop.py
random : [19, 9, 4, 10, 11, 8, 2]
heapified : 2
9 4
10 11 8 19
------------------------------------ pop 2: 4
9 8
10 11 19
------------------------------------ pop 4: 8
9 19
10 11
------------------------------------ pop 8: 9
10 19
11
------------------------------------ pop 9: 10
11 19
------------------------------------ pop 10: 11
19
------------------------------------ pop 11: 19
------------------------------------ pop 19: ------------------------------------ inorder : [2, 4, 8, 9, 10, 11, 19]

使用heapreplace()可以删除现有元素和用新的值替换已存元素.

import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data heapq.heapify(data)
print 'start:'
show_tree(data) for n in [0, 7, 13, 9, 5]:
smallest = heapq.heapreplace(data, n)
print 'replace %2d with %2d:' % (smallest, n)
show_tree(data)

这个功能让你维持了一个固定大小的堆, 这在具有优先级任务队列中是很用的.

$ python heapq_heapreplace.py
start: 2
9 4
10 11 8 19
------------------------------------ replace 2 with 0: 0
9 4
10 11 8 19
------------------------------------ replace 0 with 7: 4
9 7
10 11 8 19
------------------------------------ replace 4 with 13: 7
9 8
10 11 13 19
------------------------------------ replace 7 with 9: 8
9 9
10 11 13 19
------------------------------------ replace 8 with 5: 5
9 9
10 11 13 19
------------------------------------

数据极值

heapq也包含了2个用于检查迭代对象中最大或最小的值范围. 使用nlargest()和nsmallest()可以获得相对最小或最大的n个数, n一般大于1, 但在有些情况下不能获得正确的值.

import heapq
from heapq_heapdata import data print 'all :', data
print '3 largest :', heapq.nlargest(3, data)
print 'from sort :', list(reversed(sorted(data)[-3:]))
print '3 smallest:', heapq.nsmallest(3, data)
print 'from sort :', sorted(data)[:3]
$ python heapq_extremes.py
all : [19, 9, 4, 10, 11, 8, 2]
3 largest : [19, 11, 10]
from sort : [19, 11, 10]
3 smallest: [2, 4, 8]
from sort : [2, 4, 8]

Navigation

PyMOTW: heapq¶的更多相关文章

  1. python中使用heapq查看最大与最小的N个元素列表

    怎么从一个集合中获取最大或最小的N个元素列表? heapq模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题. In [39]: import heapq In [ ...

  2. 每日一“酷”之heapq

    作用:heapq模块实现一个适用于Python列表的最小堆排序算法 堆(heap)是一个属性数据结构,其中子节点与父节点是一种有序关系.二叉堆是一种特殊的堆,二叉堆是完全二元树(二叉树)或者是近似完全 ...

  3. python heapq

    这个模块(build-in)实现了一个堆的数据结构,完美的解决了Top-K问题,以后解决Top-K问题的时候,直接把这个模块拿来用就可以了 注意,默认的heap是一个小顶堆! heapq模块提供了如下 ...

  4. Python使用heapq实现小顶堆(TopK大)、大顶堆(BtmK小)

    Python使用heapq实现小顶堆(TopK大).大顶堆(BtmK小) | 四号程序员 Python使用heapq实现小顶堆(TopK大).大顶堆(BtmK小) 4 Replies 需1求:给出N长 ...

  5. [Python] heapq简介

    [Python] heapq简介 « Lonely Coder [Python] heapq简介 judezhan 发布于 2012 年 8 月 8 日 暂无评论 发表评论 假设你需要维护一个列表,这 ...

  6. Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET

    Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET Python -- 堆数据结构 heapq 分类: Python 2012-09 ...

  7. Python heapq 模块的实现 - A Geek's Page

    Python heapq 模块的实现 - A Geek's Page Python heapq 模块的实现

  8. heapq

    heapq-Guest-ChinaUnix博客 假设你需要维护一个列表,这个列表不断有新的元素加入,你需要在任何时候很方便的得到列表中的最大(小)值,因此要求列表始终处于排序完毕状态,怎么办呢 最简单 ...

  9. Python系列之heapq内置模块

    heapq 是 python 的内置模块,源码位于 Lib/heapq.py ,该模块提供了基于堆的优先排序算法. 堆的逻辑结构就是完全二叉树,并且二叉树中父节点的值小于等于该节点的所有子节点的值.这 ...

随机推荐

  1. Denny Zhang:一辈子做一个自由职业者

    程序猿訪谈录供稿 Denny是一个旅居美国的自由职业者,这是一份让人羡慕的职业,选择这个职业意味着他已经实现某种程度上的经济自由,能够最大限度的做自己喜欢的事情,对他来说,选择自由职业作为自己终生的事 ...

  2. 总线接口与计算机通信(一)I2C总线

    1.  I2C总线的基本概念    1)发送器(Transmitter):发送数据到总线的器件    2)接收器(Receiver):从总线接收数据的器件    3)主机(Master):初始化发送. ...

  3. 基于visual Studio2013解决C语言竞赛题之1023判断排序

         题目 解决代码及点评 /* 23. 有10个两位整数,把这些数作以下变化,如果它是素数, 则把它乘以2,若它是偶数则除以2,其余的数减1, 请将变化后的10个数按从小到大 ...

  4. Qt的setMouseTracking使用

    bool mouseTracking 这个属性保存的是窗口部件跟踪鼠标是否生效. 如果鼠标跟踪失效(默认),当鼠标被移动的时候只有在至少一个鼠标按键被按下时,这个窗口部件才会接收鼠标移动事件. 如果鼠 ...

  5. 树后台数据存储(採用webmethod)

    树后台数据存储 关于后台数据存储将集中在此篇解说 /* *作者:方浩然 *日期:2015-05-26 *版本号:1.0 */ using System; using System.Collection ...

  6. Swift - 给表格TableView添加页眉和页脚

    UITableView具有var tableHeaderView:UIView?属性和var tableFooterView:UIView?属性,可以通过给其赋值来创建列表TableView的页眉和页 ...

  7. 如何使用Reaver破解Wi-Fi网络的WPA密码

    via: http://lifehacker.com/5873407/how-to-crack-a-wi+fi-networks-wpa-password-with-reaver 译者:Mr小眼儿 本 ...

  8. activemq java版本要求

    <pre name="code" class="html">activemq: redis01:/root# cp apache-activemq- ...

  9. 14.1.1 InnoDB as the Default MySQL Storage Engine

    14.1 Introduction to InnoDB 14.1.1 InnoDB as the Default MySQL Storage Engine 14.1.2 Checking InnoDB ...

  10. D3D 练习小框架

    自己练习D3D 程序搭的小框架,记录在这里,将来看到好回顾自己独自摸索的苦逼样子. #pragma once #pragma comment(lib,"d3d9.lib") #pr ...