python - 最大堆抛出索引越界

标签 python algorithm tree heap binary-heap

下面是我的最大堆实现。我真的可以弄清楚为什么我得到索引越界错误。我已将数组分配给 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/

相关文章:

python - 使用 Pandas 计算特定列中具有相同值的行

python - 在不删除python中的字符的情况下拆分具有不同条件的字符串

python - SQLAlchemy 关系

c++ - Dijkstra 算法 : memory consumption

python - "Not in function"递归函数错误

c++ - 使用多个标志在 Boost Property Tree 1.50 中使用 read_xml() 时

python - 从 pandas 数据框中的变量中提取数值

c - 栈中元素的平均生命周期

algorithm - 带堆栈的斐波那契递归

algorithm - 用树数据结构解决难题