# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
import heapq
#--------------------create new heap
nums = [2,5,1,6,9,0]
heap = []
for num in nums:
heapq.heappush(heap,num)
print(heap)
print([heapq.heappop(heap) for _ in range(len(heap))])
#result:
#[0, 5, 1, 6, 9, 2]
#[0, 1, 2, 5, 6, 9]
#--------------------create new heap in place
nums = [2,5,1,6,9,0]
heapq.heapify(nums)
print([heapq.heappop(nums) for _ in range(len(nums))])
#result:
#[0, 1, 2, 5, 6, 9]
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
import heapq
#--------------------create Max heap
nums = [2,5,1,6,9,0]
heap = []
for num in nums:
heapq.heappush(heap,-num)
print(heap)
print([-heapq.heappop(heap) for _ in range(len(heap))])
#result
#[-9, -6, -1, -2, -5, 0]
#[9, 6, 5, 2, 1, 0]
#--------------------create topK, minK
nums = [2,5,1,6,9,0]
heapq.heapify(nums)
print(heapq.nlargest(4, nums))
print(heapq.nsmallest(4, nums))
#result
#[9, 6, 5, 2]
#[0, 1, 2, 5]
heapq库,大顶堆,小顶堆的使用笔记
本文介绍了如何在在线Python编译器中使用heapq模块创建堆、最大堆以及获取前K个最大值和最小值。示例代码展示了heapify函数的应用和heappush、heappop等操作。
摘要由CSDN通过智能技术生成