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

问题描述

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

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


解决方法

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,9]
     _heapify_max(a)
    
     print('Heap obtained from _heappop_max() : ',a)
    
  2. 或者您可以将列表与-1乘以并使用minheap本身。

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

我希望这会有所帮助。