python3,python小根堆操作

 2023-10-30 阅读 32 评论 0

摘要:一、通過list建堆 1、heapify()可以把list變成堆 from heapq import *a=[0,6,3,2] heapify(a) while len(a)>0:print(heappop(a)) 2、直接對空list進行heappush操作 b=[] heappush(b,5) heappush(b,3) heappush(b,2) heappush(b,0) while len(b)>0:print(heappo

一、通過list建堆

1、heapify()可以把list變成堆

from heapq import *a=[0,6,3,2]
heapify(a)
while len(a)>0:print(heappop(a))

2、直接對空list進行heappush操作

b=[]
heappush(b,5)
heappush(b,3)
heappush(b,2)
heappush(b,0)
while len(b)>0:print(heappop(b))

3、如果list非空,但是是有序的,可以通過heappop和heappush操作

c=[0,2,3,5]
heappush(c,4)
while len(c)>0:print(heappop(c))

二、pop和push

最普通的heappop和heappush在上面已經演示過了。

python3。heapq還提供了兩個函數,為pop和push的合并,這樣可以保證堆大小不變且效率更高一些。

heapq.heappushpop(heap, item)

heapq.heapreplace(heap, item)

他們的區別是heappushpop為先push再pop,另一個相反。

三、其他

heapq.merge(*iterables,?key=None,?reverse=False)??

python大頂堆,合并heap

heapq.nlargest(n,?iterable,?key=None)

輸出heap中最大的n個元素

heapq.nsmallest(n,?iterable,?key=None)

輸出heap中最小的n個元素

這三個函數返回值都是generator

for i in merge(a,b,c):print(i)
for i in nlargest(2,c):print(i)
for i in nsmallest(2,c):print(i)

python 二維list?

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/167076.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息