max heap in python inbuilt
# Python3 program to demonstrate working of heapq
from heapq import heappop, heappush, heapify
# Creating empty heap
heap = []
heapify(heap)
# Adding items to the heap using heappush
# function by multiplying them with -1
heappush(heap, -1 * 10)
heappush(heap, -1 * 30)
heappush(heap, -1 * 20)
heappush(heap, -1 * 400)
# printing the value of maximum element
print("Head value of heap : "+str(-1 * heap[0]))
# printing the elements of the heap
print("The heap elements : ")
for i in heap:
print(-1 * i, end = ' ')
print("\n")
element = heappop(heap)
# printing the elements of the heap
print("The heap elements : ")
for i in heap:
print(-1 * i, end = ' ')
# Python code to demonstrate working of
# heapify(), heappush() and heappop()
# importing "heapq" to implement heap queue
import heapq
# initializing list
li = [5, 7, 9, 1, 3]
# using heapify to convert list into heap
heapq.heapify(li)
# printing created heap
print ("The created heap is : ",end="")
print (list(li))
# using heappush() to push elements into heap
# pushes 4
heapq.heappush(li,4)
# printing modified heap
print ("The modified heap after push is : ",end="")
print (list(li))
# using heappop() to pop smallest element
print ("The popped and smallest element is : ",end="")
print (heapq.heappop(li))