Python——heap

通过优先队列可以构造堆,堆是一种实用的数据结构。尽管Python中没有独立的堆类型,但是包含了一些对操作函数的模块,这个模块叫heapq,主要的操作包含如下几个:

heappush(heap,x):x元素插入堆
heappop(heap):弹出对中最小元素
heapify(heap):将heap属性强制应用到任意一个列表
hrapreplace(heap,x):将heap中最小元素弹出,同时x元素入堆
hlargest(n,iter):返回iter中第n大的元素
hsmallest(n,iter):返回iter中第n小的元素

堆的定义和使用如下:

>>> from heapq import *
>>> from random import shuffle
>>> x=[1,2,3,4,5,6]
>>> shuffle(x)
>>> heap=[]
>>> for i in x:
    heappush(heap,i)
>>> heap
[1, 3, 2, 6, 4, 5]
>>>

注:shuffle函数将列表顺序打乱
堆元素的追加:

>>> heap
[1, 3, 2, 6, 4, 5]
>>> heappush(heap,0)
>>> heap
[0, 3, 1, 6, 4, 5, 2]
>>>  

删除堆中元素:

>>> heap
[0, 3, 1, 6, 4, 5, 2]
>>> heappop(heap)
0
>>> heap
[1, 3, 2, 6, 4, 5]
>>> heappop(heap)
1
>>> heap
[2, 3, 5, 6, 4]
>>>

heapify函数将列表生成堆:

>>> x=[1,4,2,3,5,4]
>>> heapify(x)
>>> x
[1, 3, 2, 4, 5, 4]
>>> heappop(x)
1
>>> heappop(x)
2
>>> x
[3, 4, 4, 5]
>>> 

hrapreplace函数弹出最小元素将另一个元素加入堆:

>>> x
[3, 4, 4, 5]
>>> heapreplace(x,0)
3
>>> x
[0, 4, 4, 5]
>>> 
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值