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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yysyangyangyangshan/article/details/84963558

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

猜你喜欢

转载自blog.csdn.net/yysyangyangyangshan/article/details/84963558