最大堆抛出索引超出范围

2024-04-25 19:40:11 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的最大堆实现。我真的能弄明白为什么索引越界错误。我已将数组分配给self.堆在

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])

错误:

^{pr2}$

Tags: andselfindexlenifdef错误tmp
1条回答
网友
1楼 · 发布于 2024-04-25 19:40:11

你有这个代码:

    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]:

在检查索引是否超出列表的界限之前,您尝试索引到列表中。此外,您需要检查索引以查看它是否在范围内,而不是检查该索引的内容是否在范围内。在

它应该是:

^{pr2}$

我不清楚你的根是0还是1。在

如果根节点位于list[0],那么您的计算应该是(2*index) + 1和{}。您的计算假设根位于list[1]。在

相关问题 更多 >