About
@start-editable@
class BinHeap(): def _init_(self): self.heapList = [0] self.currentSize = 0
def upHeapp(self,i):
while(i//2):
if self.heapList[i]<self.heapList[i//2]:
self.heapList[i],self.heapList[i//2]=self.heapList[i//2],self.heapList[i]
i=i//2
return
def insert(self,k):
self.heapList.append(k)
self.currentSize+=1
self.upHeapp(self.currentSize)
return
""" This method defines the downheap function when removing min
"""
def downHeap(self,i):
while(i*2)<=self.currentSize:
mc=self.minChild(i)
if self.heapList[i]>self.heapList[mc]:
self.heapList[i],self.heapList[mc]=self.heapList[mc],self.heapList[i]
i=mc
return
def minChild(self,i):
if (i*2)+1>self.currentSize:
return i*2
else:
if self.heapList[i*2]<self.heapList[(i*2)+1]:
return i*2
else:
return (i*2)+1
def delMin(self):
if len(self.heapList)==1:
return "Not possible"
root=self.heapList[1]
self.heapList[1]=self.heapList[self.currentSize]
self.heapList.pop(self.currentSize)
self.currentSize-=1
self.downHeap(1)
return
def buildHeap(self,alist):
i = len(alist) // 2
self.currentSize = len(alist)
self.heapList = [0] + alist[:]
while (i > 0): #// \label{lst:bh:loop}
self.downHeap(i)
i = i - 1
#create a method to print the contents of the heap in level order
def printHeap(self):
print(self.heapList)
def main(): heap = BinHeap() arraySize = int(input()) arr = list(map(int, input().split())) heap.buildHeap(arr) inputs = int(input()) while inputs > 0: command = input() operation = command.split() if (operation[0] == "I"): heap.insert(int(operation[1])) heap.printHeap() elif (operation[0] == "R"): heap.delMin() heap.printHeap() inputs -= 1
if _name_ == '_main_': main()