python 大根堆
python默认的都是小根堆,实现数字的大根堆,可在堆化前把数字 乘以 -1 ,输出时 再 乘以 -1 变回原值。
比如: [5, 20, 6],堆化前用列表推导式把列表转为: [-5, -20, -6]
import heapq
import random
data = list(range(1,30))
random.shuffle(data) # 打乱顺序
data = data[:12] # 取12个数字 [17, 14, 29, 1, 2, 7, 25, 15, 11, 24, 16, 22]
data_b = [-i for i in data] # 变为相反数,模拟大根堆
heapq.heapify(data) # 堆化 小跟堆
print(heapq.nlargest(3, data)) # [29, 25, 24] 输出三个最大值
for i in range(12):
print(heapq.heappop(data), end='\t')
# 1 2 7 11 14 15 16 17 22 24 25 29
print()
heapq.heapify(data_b) # 堆化 大根堆
for i in range(12):
print(-heapq.heappop(data_b), end='\t') # 输出相反数
# 29 25 24 22 17 16 15 14 11 7 2 1
print()