Python Bkt列表索引超出范围

2024-06-01 01:46:34 发布

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

我是Python新手,我想学习回溯算法。我看了一些教程并创建了以下代码:

x = []
pod = []
class def_pod:
    ins1 = 0
    ins2 = 0
    def __init__(self, name):
        self.name = name
ins_start = int(input("Insula de start: "))
n = int(input("Numar de poduri: "))
def Plimbare (insula_crt, k):
    if n==k:
        print(x)
    else:
        for i in range(0,n-1):
            if POSIBIL(i,k,insula_crt):
                x[k] = i
                if insula_crt == pod[i].ins1:
                    ins=pod[i].ins2
                else:
                    ins=pod[i].ins1
                Plimbare(ins,k+1)

def POSIBIL (alfa,k,ins_crt):
    for j in range(0,n-1):
        if x[j] == alfa:
            return False
    return pod[alfa].ins1 == ins_crt or pod[alfa].ins2 == ins_crt

print ("Lansare executie program: \n")
Plimbare(ins_start,0)

但是我有一些错误,因为我的数组超出了范围,我不知道我能做些什么来解决这个问题。你能帮助我吗?很抱歉,如果我的问题不那么相关,但正如我所说,我是新来的。。你知道吗


Tags: nameselfinputifdefstartintpod
1条回答
网友
1楼 · 发布于 2024-06-01 01:46:34

Resolved in comments:

First time your POSIBIL() function called, x is empty list and you still want to access upto nth element in that list 

instead of x[k] = i, use x.append(i) – Jay Parikh 

相关问题 更多 >