python入门:关于堆操作的一个模块heapq及其函数



若有帮助到你,记得点赞u。

# -*- coding: utf-8 -*-
"""
Created on Fri Apr  6 20:25:02 2018

@author: Lelouch_C.C
"""
#python中没有独立的对类型,只有一个包含一些堆操作函数的模块heapq,q指queue队列
from heapq import *
from random import shuffle
data=list(range(10))
shuffle(data)             #shuffle英文意思是洗牌,这里进行随机打乱data中元素顺序
heap=[]
for n in data:
    heappush(heap,n)      #将n入堆
print(heap)
#输出:[0, 1, 2, 4, 6, 9, 3, 7, 5, 8],输出结果可能不同
heappush(heap,0.5)
print(heap)
#输出:[0, 0.5, 2, 4, 1, 9, 3, 7, 5, 8, 6],输出结果可能不同

"""
上述排序并不严格,但也并不随意.
遵循堆属性:i位置处的元素总比2i和2i+1位置处的元素小.
注意:i从1开始.
"""

heappop(heap)             
#heappop会弹出最小元素,一般来说都是在索引0处,
#并且在保证堆属性的条件下,会将剩余的元素中最小的那个占据索引0的位置
print(heap)
#输出:[0.5, 1, 6, 2, 5, 8, 7, 4, 3, 9],输出结果可能不同
heappop(heap)
print(heap)
#输出:[1, 3, 2, 4, 5, 9, 6, 8, 7],输出结果可能不同

heap1=[5,8,4,6,1,7,9,3,2]
heapify(heap)               
#heapify将任意的列表作为参数,并通过尽可能少的操作使得列表满足堆属性。
#注意:对于任意的列表,不能直接用heappush、heappop、heapreplace等,必须先用heapify进行合法化
print(heap)
#输出:[1, 2, 5, 3, 4, 7, 8, 6, 9]

heapreplace(heap,0.5)
#heapreplace会弹出最小元素,并将新元素推入,返回被推出的最小值
print(heap)
#输出:[0.5, 2, 6, 4, 3, 7, 8, 9, 5]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章