python3入门之堆（heapq）

4 篇文章 0 订阅
堆是一个二叉树，其中每个父节点的值都小于或等于其所有子节点的值。整个堆的最小元素总是位于二叉树的根节点。python的heapq模块提供了对堆的支持。



heapq.heappush(heap,item)

>>> import heapq
>>> h = []
>>> heapq.heappush(h,2)
>>> h
[2]

heapq.heapify(list)

>>> list = [1,2,3,5,1,5,8,9,6]
>>> heapq.heapify(list)
>>> list
[1, 1, 3, 5, 2, 5, 8, 9, 6]

heapq.heappop(heap)

>>> list
[1, 1, 3, 5, 2, 5, 8, 9, 6]
>>> heapq.heappop(list)
1
>>> list
[1, 2, 3, 5, 6, 5, 8, 9]

heapq.heapreplace(heap.item)

>>> list
[1, 2, 3, 5, 6, 5, 8, 9]
>>> heapq.heapreplace(list,99)
1
>>> list
[2, 5, 3, 9, 6, 5, 8, 99]

heapq.heapreplace(heap,item)

>>> list
[2, 5, 3, 9, 6, 5, 8, 99]
>>> heapq.heappushpop(list,6)
2
>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.heappushpop(list,1)
1
>>> list
[3, 5, 5, 9, 6, 6, 8, 99]

heapq.merge（…）

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> h
[1000]
>>> for i in heapq.merge(h,list):
...     print(i,end=" ")
...
3 5 5 9 6 6 8 99 1000 

heapq.nlargest(n,heap)

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.nlargest(3,list)
[99, 9, 8]
>>>


heapq.nsmallest(n,heap)

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.nsmallest(3,list)
[3, 5, 5]
• 4
点赞
• 27
收藏
觉得还不错? 一键收藏
• 6
评论
06-26 2489
03-23 7060
10-16 308
09-26 1153
03-30 1163
08-09 1923
03-14 899
09-11 2168
12-30 224

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。