listheapq

How to add list to heapq in python


How can i add the input list to heap directly?,Where some of the inbuild function used to push,get min,extract min but how to extract the maximum from the heap. some functions like..

  1. heapify(iterable) :- This function is used to convert the iterable into a heap data structure. i.e. in heap order.

  2. heappush(heap, ele) :- This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained.

  3. heappop(heap) :- This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained.


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



Solution

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

    And for maxheap

    1. heapq implements function with suffix _max example : _heapify_max, _heapreplace_max, etc.

       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. Or you can multiple the list with -1 and use minheap itself.

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

    I hope this helps.