0

如何直接将输入列表添加到堆中?,其中一些inbuild函数用于push,get min,extract min但是如何从堆中提取最大值。一些功能,如..

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

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

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


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")


4

1 回答 1

0
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)

而对于 maxheap

  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.
    

我希望这有帮助。

于 2020-08-12T11:27:29.067 回答