2017-06-01 90 views
0

我是Python新手,我想学习Backtracking算法。我看了一些教程,我创造了这个代码:Python Bkt - 列表索引超出范围

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) 

但我的事实,我的数组是超出范围,我不知道我能做些什么来解决这个链接的一些错误。你可以帮我吗?对不起,如果我的问题不那么相关,但正如我所说,我是新..

+0

第一次你的'POSIBIL()'函数称为'x'为空列表,并且您仍然希望访问该列表中的第n个元素 – kuro

+0

而不是x [k] = i,请使用x.append(i) –

+0

非常感谢。我认为我的问题现在已经解决了。 :) –

回答

0

解决的评论:

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