下面是我的最大堆实现。我真的可以弄清楚为什么我得到索引越界错误。我已将数组分配给 self.heap
class heap:
def __init__(self):
self.heapsize=0
self.heap=[0]
def builheap(self,list):
self.heapsize = len(list)
self.heap=list
for i in range(len(list)//2, 0, -1):
self.maxheap(self.heap,i)
def maxheap(self, list, index):
if list[2*index]<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if list[2*index+1]<= self.heapsize and list[2*index+1]>list[index]:
largest=list[2*index+1]
if largest!=index:
tmp = list[index]
list[index] = list[largest]
list[largest] = tmp
maxheap(list,largest)
h=heap()
h.builheap([16,14,10,8,7,9,3,2,4,1])
错误:
Traceback (most recent call last):
File "heap.py", line 24, in <module>
h.builheap([16,14,10,8,7,9,3,2,4,1])
File "heap.py", line 9, in builheap
self.maxheap(self.heap,i)
File "heap.py", line 11, in maxheap
if list[2*index]<=self.heapsize and list[2*index]>list[index]:
IndexError: list index out of range
最佳答案
你有这个代码:
if list[2*index]<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if list[2*index+1]<= self.heapsize and list[2*index+1]>list[index]:
在检查索引是否超出列表范围之前,您正在尝试对列表进行索引。此外,您想检查索引以查看它是否在范围内,而不是检查该索引处的内容是否在范围内。
应该是:
if 2*index<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if 2*index+1<= self.heapsize and list[2*index+1]>list[index]:
我不清楚你的根是在 0 还是 1。
如果根节点在 list[0]
,那么你的计算应该是 (2*index) + 1
和 (2*index)+ 2
。您的计算假定根位于 list[1]
。
关于python - 最大堆抛出索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39795082/