少说话多写代码之Python学习059——标准模块(堆)

栏目: Python · 发布时间: 7年前

内容简介:heap堆是一种优先队列,用优先队列可以以任意顺序增加对象。并且在任何时间找到最小元素。Python中有一个包含一些堆操作函数的模块heapq。包括如下函数,heappush(heap,x) 将x入堆heappop(heap) 将堆中最小的元素弹出

heap堆是一种优先队列,用优先队列可以以任意顺序增加对象。并且在任何时间找到最小元素。Python中有一个包含一些堆操作函数的模块heapq。包括如下函数,

heappush(heap,x) 将x入堆

heappop(heap) 将堆中最小的元素弹出

heapify(heap) 将heap属性强制应用到任意列表

heapreplace(heap,x) 将堆中最小的元素弹出,同时将x入堆

nlargest(n,iter) 返回iter中第n大的元素

nsmallest(n,iter) 返回iter中第n小的元素看下面的使用,

from heapq import  *
from random import shuffle

data= [0,1,2,3,4,5,6,7,8,9]
shuffle(data)
heap =[]
for n in data:
    heappush(heap,n)
print(heap)
输出
[0, 1, 2, 3, 7, 6, 5, 9, 4, 8]
for n in data:
    heappush(heap,0.5)
print(heap)
输出
[0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 2, 4, 7, 1, 3, 0.5, 9, 6, 8, 0.5, 5]

heappush用于增加堆的项,用于堆函数建立的列表中,因为堆的列表有一定的顺序。这里虽然看起来顺序随意,但是是有规律的,位于i处的元素总是比i/2处的元素大。这个特性称之为堆属性。

heappop弹出最小的元素,一般弹出索引0处的元素,弹出后确保剩余元素中最小的元素占在这个位置。

print(heappop(heap))
print(heappop(heap))
print(heap)
输出
0
0.5
[0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1, 3, 9, 6, 7, 8, 5, 2, 4]

heapify使用任意列表作为参数,将其转换为合法的堆。

heap=[1,2,3,5,4,8,9.7]
heapify(heap)
print(heap)
输出
[1, 2, 3, 5, 4, 8, 9.7]

heapreplace弹出堆的最小元素,并且将新元素推入。它比heappop后再heappush效率高。

heapreplace(heap,0.5)
print(heap)
输出
[0.5, 2, 3, 5, 4, 8, 9.7]
heapreplace(heap,10)
print(heap)
输出
[2, 4, 3, 5, 10, 8, 9.7]

堆的主要函数就了解到这里,记住堆的属性:i位置处的元素总比2i以及2i+1索引处的元素小。

工程文件下载: https://download.csdn.net/download/yysyangyangyangshan/10844403


以上所述就是小编给大家介绍的《少说话多写代码之Python学习059——标准模块(堆)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms and Data Structures

Algorithms and Data Structures

Kurt Mehlhorn、Peter Sanders / Springer / 2008-08-06 / USD 49.95

Algorithms are at the heart of every nontrivial computer application, and algorithmics is a modern and active area of computer science. Every computer scientist and every professional programmer shoul......一起来看看 《Algorithms and Data Structures》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具