【发布时间】:2022-01-22 04:28:57
【问题描述】:
我正在学习数据结构,但我的代码无法正常工作..我尝试调试但找不到任何东西(似乎 heapifyinsert() 没有做任何事情)
这是我的代码:
class Heap:
def __init__(self,size):
self.heap=[None]*(size+1)
self.heapsize=0
self.maxheapsize=size+1
def levelordertransversal(self):
if not self.heap:
raise Exception('Heap doesn\'t exists')
for x in range(1,self.heapsize+1):
print(self.heap[x])
def heapifyinsert(self,index,heaptype):
heaptype=heaptype.title()
parentindex=int(index/2)
if parentindex<=1:
return
if heaptype=='Min':
if self.heap[index]<self.heap[parentindex]:
temp=self.heap[index]
self.heap[index]=self.heap[parentindex]
self.heap[parentindex]=temp
self.heapifyinsert(parentindex,heaptype)
elif heaptype=='Max':
if self.heap[index]>self.heap[parentindex]:
temp=self.heap[index]
self.heap[index]=self.heap[parentindex]
self.heap[parentindex]=temp
self.heapifyinsert(parentindex,heaptype)
def insertnode(self,nodevalue,heaptype):
if self.heapsize+1==self.maxheapsize:
raise Exception('Heap is full!!')
self.heap[self.heapsize+1]=nodevalue
self.heapsize+=1
self.heapifyinsert(self.heapsize,heaptype)
h=Heap(5)
h.insertnode(4,'Max')
h.insertnode(5,'Max')
h.insertnode(2,'Max')
h.insertnode(1,'Max')
h.levelordertransversal()
当前输出:
4
5
2
1
预期输出:
5
4
2
1
因此,在上面的代码中,我尝试从索引位置 1 开始实现堆(为简单起见),在 heapifyinsert() 方法中,我们采用 parentindex 并检查父索引处的值是否更大或更小堆类型和交换值
任何帮助或线索将不胜感激..谢谢!
【问题讨论】:
-
您希望
heaptype=heaptype.title()的结果是什么?此指令更改作为变量提供给函数的 heaptype 的值。 -
@itprorh66 先生,这个想法是用户可以输入堆类型而不管它是什么情况(bcz先生,函数内部堆类型的条件写在标题中)
-
好吧,每天都学点新东西。
标签: python data-structures heap