我试图用python创建一个二进制堆,但在打印时遇到了麻烦。我确保程序中的逻辑是正确的,但是当我想要打印它时,我得到了错误的结果。这是我想要的程序输出:
输入:
6
1 2
1 3
1 7
2
3
2
输出:
7
3
这是我的节目:
class BinaryHeap:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def parent(self, i):
return (i - 1)//2
def left(self, i):
return 2*i + 1
def right(self, i):
return 2*i + 2
def get(self, i):
return self.items[i]
def get_max(self):
if self.size() == 0:
return None
return self.items[0]
def extract_max(self):
if self.size() == 0:
return None
largest = self.get_max()
self.items[0] = self.items[-1]
del self.items[-1]
self.max_heapify(0)
return largest
def max_heapify(self, i):
l = self.left(i)
r = self.right(i)
if (l <= self.size() - 1 and self.get(l) > self.get(i)):
largest = l
else:
largest = i
if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
largest = r
if (largest != i):
self.swap(largest, i)
self.max_heapify(largest)
def swap(self, i, j):
self.items[i], self.items[j] = self.items[j], self.items[i]
def insert(self, key):
index = self.size()
self.items.append(key)
while (index != 0):
p = self.parent(index)
if self.get(p) < self.get(index):
self.swap(p, index)
index = p
bheap = BinaryHeap()
n = int(input())
for i in range (n):
operation= input('What would you like to do? ').split()
if operation == 1:
data = int(operation[1])
bheap.insert(data)
elif operation == 2:
print('Maximum value: {}'.format(bheap.get_max()))
elif operation == 3:
print('Maximum value removed: {}'.format(bheap.extract_max()))
elif operation == 4:
break
我需要你的意见来修正它
operation
是一个列表(您调用了split
),但在if
语句中将其作为int进行比较。此外,您还应将其与“1”、“2”。。。不是1,2因此:
如果您只想在输出中使用
7
和3
,并且只有在输入被完全处理之后,才应该删除那些详细的print
语句(在其中输出短语),并在列表中收集输出,例如:相关问题 更多 >
编程相关推荐