heapq 模块提供了堆算法。heapq是一种子节点和父节点排序的树形数据结构。这个模块提供heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2]。为了比较不存在的元素被人为是无限大的。heap最小的元素总是[0]。

打印 heapq 类型

import math

import random

from cStringIO import StringIO

def show_tree(tree, total_width=36, fill=' '):

output = StringIO()

last_row = -1

for i, n in enumerate(tree):

if i:

row = int(math.floor(math.log(i+1, 2)))

else:

row = 0

if row != last_row:

output.write('\n')

columns = 2**row

col_width = int(math.floor((total_width * 1.0) / columns))

output.write(str(n).center(col_width, fill))

last_row = row

print output.getvalue()

print '-' * total_width

print

return

data = random.sample(range(1,8), 7)

print 'data: ', data

show_tree(data)

打印结果

data: [3, 2, 6, 5, 4, 7, 1]

3

2 6

5 4 7 1

-------------------------

heapq.heappush(heap, item)

push一个元素到heap里, 修改上面的代码

heap = []

data = random.sample(range(1,8), 7)

print 'data: ', data

for i in data:

print 'add %3d:' % i

heapq.heappush(heap, i)

show_tree(heap)

打印结果

data: [6, 1, 5, 4, 3, 7, 2]

add 6:

6

------------------------------------

add 1:

1

6

------------------------------------

add 5:

1

6 5

------------------------------------

add 4:

1

4 5

6

------------------------------------

add 3:

1

3 5

6 4

------------------------------------

add 7:

1

3 5

6 4 7

------------------------------------

add 2:

1

3 2

6 4 7 5

------------------------------------

根据结果可以了解,子节点的元素大于父节点元素。而兄弟节点则不会排序。

heapq.heapify(list)

将list类型转化为heap, 在线性时间内, 重新排列列表。

print 'data: ', data

heapq.heapify(data)

print 'data: ', data

show_tree(data)

打印结果

data: [2, 7, 4, 3, 6, 5, 1]

data: [1, 3, 2, 7, 6, 5, 4]

1

3 2

7 6 5 4

------------------------------------

heapq.heappop(heap)

删除并返回堆中最小的元素, 通过heapify() 和heappop()来排序。

data = random.sample(range(1, 8), 7)

print 'data: ', data

heapq.heapify(data)

show_tree(data)

heap = []

while data:

i = heapq.heappop(data)

print 'pop %3d:' % i

show_tree(data)

heap.append(i)

print 'heap: ', heap

打印结果

data: [4, 1, 3, 7, 5, 6, 2]

1

4 2

7 5 6 3

------------------------------------

pop 1:

2

4 3

7 5 6

------------------------------------

pop 2:

3

4 6

7 5

------------------------------------

pop 3:

4

5 6

7

------------------------------------

pop 4:

5

7 6

------------------------------------

pop 5:

6

7

------------------------------------

pop 6:

7

------------------------------------

pop 7:

------------------------------------

heap: [1, 2, 3, 4, 5, 6, 7]

可以看到已排好序的heap。

heapq.heapreplace(iterable, n)

删除现有元素并将其替换为一个新值。

data = random.sample(range(1, 8), 7)

print 'data: ', data

heapq.heapify(data)

show_tree(data)

for n in [8, 9, 10]:

smallest = heapq.heapreplace(data, n)

print 'replace %2d with %2d:' % (smallest, n)

show_tree(data)

打印结果

data: [7, 5, 4, 2, 6, 3, 1]

1

2 3

5 6 7 4

------------------------------------

replace 1 with 8:

2

5 3

8 6 7 4

------------------------------------

replace 2 with 9:

3

5 4

8 6 7 9

------------------------------------

replace 3 with 10:

4

5 7

8 6 10 9

------------------------------------

heapq.nlargest(n, iterable) 和 heapq.nsmallest(n, iterable)

返回列表中的n个最大值和最小值

data = range(1,6)

l = heapq.nlargest(3, data)

print l # [5, 4, 3]

s = heapq.nsmallest(3, data)

print s # [1, 2, 3]

PS:一个计算题构建元素个数为 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

结果:

更多Python中heapq模块的用法相关文章请关注PHP中文网!

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

python中heapq的库是什么_Python中heapq模块的用法相关推荐

  1. python添加库详细教程_Python 中如何自动导入缺失的库?|python基础教程|python入门|python教程...

    https://www.xin3721.com/eschool/pythonxin3721/ 在写 Python 项目的时候,我们可能经常会遇到导入模块失败的错误:ImportError: No mo ...

  2. python包和库的区别_python中模块、包、库的区别和使用

    模块:就是.py文件,里面定义了一些函数和变量,需要的时候就可以导入这些模块. 包:在模块之上的概念,为了方便管理而将文件进行打包.包目录下第一个文件便是 __init__.py,然后是一些模块文件和 ...

  3. python之33个关键字详解_Python 中的关键字 with 详解

    在 Python 2.5 中,with关键字被加入.它将常用的 try ... except ... finally ...模式很方便的被复用.看一个最经典的例子: with open('file.t ...

  4. python里删除range里的数字_python中range函数与列表中删除元素

    一.range函数使用 range(1,5)   代表从1到4(不包含5),结果为:1,2,3,4   ,默认步长为1 range(1,5,2)   结果为:1, 3  (同样不包含5) ,步长为2 ...

  5. python中的pd是什么意思_python中pd的用法 python中列表的用法

    python标准库中常用的网络相关模块有哪些? 1.asynchat.asyncoreasynchat是asyncore的增强版.asyncore则是异步套接字处理程序. 2.Cookie.cooki ...

  6. python里面的pip是什么意思_python中的pip是什么意思

    pip是Python的包管理器.这意味着它是一个工具,允许你安装和管理不属于标准库的其他库和依赖. 软件包管理极其重要,所以自 Python3 的 3.4 版本以及 Python2 的 2.7.9 版 ...

  7. python中的pass是什么意思_Python中pass的作用与使用教程

    Python中pass的作用与使用教程 Python中pass的作用 空语句 do nothing 保证格式完整 保证语义完整 以if语句为例,在c或c++/java中: if(true) ; //d ...

  8. python中的header是什么意思_python中header是什么意思啊

    python中的createheader什么意思 %-*s代表输入一个字符串,-号代表左对齐.后补空白,*号代表对齐宽度由输入时确定%*s代表输入一个字符串,右对齐.前补空白,*号代表对齐宽度由输入时 ...

  9. python 不安全的包或方法_Python中的10个常见安全漏洞及修复方法

    写安全的代码很困难,当你学习一门编程语言.一个模块或框架时,你会学习其使用方法.在考虑安全性时,你需要考虑如何避免代码被滥用,Python也不例外,即使在标准库中,也存在着许多糟糕的实例.然而,许多 ...

最新文章

  1. 如何成为一名优秀的web前端工程师[转]
  2. Access 导出各种格式文件
  3. Tensorflow-gpu在windows系统下的安装及使用(使用Pycharm IDE)
  4. asp.net操作Excel总结
  5. 013.Zabbix的Items(监控项)
  6. win10查看pcie设备_壹拓网科技解密WIN10系统使用向日葵开机棒远程开机需要设置几个地方...
  7. java nginx 例子_Java及nginx实现文件权限控制代码实例
  8. 【数据库系统】数据库体系结构
  9. python爬虫之requests模块2
  10. 虚拟机VMware tools安装
  11. 写代码质量改善java计划151建议——导航开始
  12. Django 解决CSRF 跨域问题总结
  13. siblings()用法
  14. 大数据学习之HDFS基础
  15. 钉钉用不同的手机签到后台怎么显示的代签到有用吗
  16. Vue3 - 组件通信(子传父)
  17. 【Web技术】929- 前端海报生成的不同方案和优劣
  18. bootloader 和 启动模式的一些理解
  19. c语言报错spawning 插1,Visual C++中error spawning cl.exe解决办法
  20. Python基于逻辑回归的糖尿病视网膜病变检测(数据集messidor_features.arff)

热门文章

  1. 理解最大回撤及Python实现
  2. Postman-APIs是干什么的?
  3. 安卓模拟器安装教程_无限多开仙境传说RO!第一安卓模拟器BlueStacks蓝叠安卓模拟器多开教程...
  4. 华文行楷字帖欣赏_毛笔行书欣赏,华文行楷在线转换,偏旁部首练字帖,
  5. 项目管理PMBOK中各知识领域过程的关系图
  6. 【小程序】常见系统API | 页面分享 | 位置信息 | 本地存储
  7. 光驱动器类有哪些最新发表的毕业论文呢?
  8. 数据分析:你的城市复工了吗?
  9. Java 8 Stream Lambda 的学习与使用
  10. 基于web的模型管理系统的设计