如何在 python 中将列表添加到 heapq

How to add list to heapq in python

如何直接将输入列表添加到堆中?,其中一些内置函数用于推送、获取最小值、提取最小值但如何从中提取最大值堆。 一些功能,如..

  1. heapify(iterable) :- 此函数用于将可迭代对象转换为堆数据结构。即按堆顺序。

  2. heappush(heap, ele) :- 此函数用于将参数中提到的元素插入堆中。调整顺序,保持堆结构。

  3. heappop(heap) :- 此函数用于从堆中删除和 return 最小元素。调整顺序,保持堆结构。


heap = [] 
heapify(heap) 
heappush(heap,  10) 
heappush(heap,  30) 
heappush(heap, 20) 
heappush(heap,  400) 


# printing the elements of the heap 

for i in heap: 
    print( i, end = ' ') 
print("\n")


import heapq

heap = []   # creates an empty heap
item = [20, 4, 8, 10, 5, 7, 6, 2, 9]
for i in item:
    heapq.heappush(heap, i)  # pushes a new item on the heap

print('Heap obtained from heappush() : ', heap)

heapq.heapify(item)  # transforms list into a heap, in-place, in linear time

print('Heap obtained from heapify() : ', item)

对于最大堆

  1. heapq 实现后缀为 _max 的函数示例:_heapify_max, _heapreplace_max,等等

     from _heapq import _heappop_max, _heapify_max, _heapreplace_max
    
     a = [20, 4, 8, 10, 5, 7, 6, 2, 9]
     _heapify_max(a)
    
     print('Heap obtained from _heappop_max() : ', a)
    
  2. 或者您可以将列表与 -1 相乘并使用 minheap 本身。

     Then 100 becomes -100, 5 becomes -5, etc.
    

希望对您有所帮助。