这里的主要问题是,当您到达内部 for 循环的末尾时,您没有返回任何内容。因此,从导致您的错误的先前递归返回 NoneType :
让我们看看你的代码,看看会发生什么:我们将通过将列表替换为 for 循环来做到这一点,这样我们就可以完全看到正在发生的事情(这不是有效的 python 代码,它仅用于演示目的:D)
rec('C','C',1)
for i in ['D','C']
path_i = 'C'+rec('D','C',2)
for j in ['C','E']
path_j = 'D' + rec('C','C',2)
'C'=='C' and 2!=1
return 'C'
好的,到目前为止一切顺利,我们有路径(path_j)'DC',所以我们将它附加到路径,现在查看最里面的循环,其中 j 现在设置为'E'
rec('C','C',1)
for i in ['D','C']
path_i = 'C'+rec('D','C',2)
for j in ['E']
path_j = 'D'+rec('E','C',2)
for k in ['B']
path_k = 'B'+rec('B','C',2)
for l in ['C']
'C'=='C' and 2!=1
return 'C'
好的,我们有另一条路。这次是 path_k = 'BC',所以让我们将它附加到路径中。但是现在我们已经用完了 k 的元素,我们需要返回一些东西
rec('C','C',1)
for i in ['D','C']
path_i = 'C'+rec('D','C',2)
for j in ['E']
path_j = 'D'+rec('E','C',2)
for k in []
return ???
目前您没有返回任何内容,因此 python 为您返回一个“NoneType”对象
rec('C','C',1)
for i in ['D','C']
path_i = 'C'+rec('D','C',2)
for j in ['E']
path_j = 'D'+NoneType
不幸的是,您现在正尝试将此 NoneType 与字符串连接,因此您的错误:
TypeError: cannot concatenate 'str' and 'NoneType' objects
为了更正,您可以只返回路径字符串:(这是现在实际有效的 python 代码)
hasht= {"A":["B", "D", "E"], "B":["C"], "C":["D", "E"], "D":["C", "E"], "E":["B"]}
paths=[]
def recusive(start, finish, val):
if start==finish and val!=1:
return start
else:
for i in hasht[start]:
path= start+ recusive(i,finish,2)
paths.append(path)
return path
print (recusive("C","C",1))
print paths
这将返回路径:
['DC', 'BC', 'EBC', 'DEBC', 'CDEBC', 'BC', 'EBC', 'CEBC']