Help me find where the loop is.
I am stuck in while loop for this heap code (python)
I intended to make code as following:
i for insert, d for delete, p for print, q for quit
input: i 20 (insert 20)
output: 0
input: i 4
output:0
input:d
output: 4 (show deleted numeric)
input: i 6
output: 0
input: d
output: 20
input:p
output: 6
input: q
output as blank
-----------
however, when I put any i+integer to insert the key, it
keeps showing me infinite zeros
ex)
i 20
0
0
0
0
0........
and I do not understand where I fell in the loop. Please
help me fix this.
below is my code, thank you ahead for the help.
----------------
class Maxheap:
def __init__(self):
self.heap = []
self.heap.append(0)
def size(self):
return len(self.heap) - 1
def isEmpty(self):
return self.size() == 0
def Parent(self,i):
return self.heap[i//2]
def Left(self,i):
return self.heap[i*2]
def Right(self,i):
return self.heap[i*2+1]
def display(self,msg = 'heap tree'):
print(msg, self.heap[1:])
def insert(self,n):
self.heap.append(n)
i=self.size()
while(i!=1 and n>self.Parent(i)):
self.heap = self.Parent(i)
i = i // 2
self.heap=n
def delete(self):
parent =1
child =2
if not self.isEmpty():
hroot = self.heap[1]
last = self.heap[self.size()]
while (child <= self.size()):
if child < self.size() and
self.Left(parent)<self.Right(parent):
child +=1
if last >= self.heap[child]:
break;
self.heap[parent] = self.heap[child]
parent = child
child *= 2;
self.heap[parent] = last
self.heap.pop(-1)
return hroot
if __name__ == "__main__":
heap = Maxheap()
data = input().split()
while True:
if data[0] == "q":
break
if data[0] == "i":
heap.insert(int(data[1]))
print("0")
if data[0] == "d":
heap.delete()
if data[0] == "p":
heap.display()
Help me find where the loop is. I am stuck in while loop for this heap code (python) I intended to make code as followin
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
Help me find where the loop is. I am stuck in while loop for this heap code (python) I intended to make code as followin
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!