我在这里遇到这个问题:
def findPaths(neighborDict, start, end, prev=0, path=[],distance = 0):
path = path + [start]
if not prev == 0:
for i in neighborDict[start]:
if i[0] is prev:
distance = distance + i[1]
if start == end:
path.append(distance)
return [path]
paths = []
for node in neighborDict[start]:
if node[0] not in path:
newpaths = findPaths(neighborDict, node[0], end, start, path,distance)
for i in newpaths:
paths.append(i)
return paths
此代码用于查找加权图中的所有路径。 这里的neighborDict存储所有节点。
我用一些节点填充了neighborDict。然后,我使用itertools创建一系列两个随机节点
neighborDict = {'1': [('3', 32), ('2', 8)], '2': [('1', 8), ('3', 2), ('4', 4)], '3': [('1', 32), ('2', 2), ('4', 16)], '4': [('5', 1), ('3', 16), ('2', 4)], '5': [('4', 1)]}
for i in range(numCities):
perms.append(str(i+1))
combs =[x for x in itertools.combinations(perms,2)]
现在,我说的是不同的输出
findPaths(neighborDict,combs[0][1],combs[0][0])
vs
findPaths(neighborDict,'2','1')
在这里,梳子[0] [1] ='2'和梳子[0] [0] ='1'。因此,它们应该提供相同的输出。
输出1为:-[['2','1',0],['2','3','1',32],['2','4','3', '1',48]] 输出2为:-[[''2','1',8],['2','3','1',34],['2','4','3','1' ,52]]