列表列表之间的最短路径

时间:2019-05-09 20:08:51

标签: python loops recursion

假设我有一个这样的列表:

[
[1, [2, 3]],
[2, [4, 5]],
[4, [6, 7]],
[3, [7]]
]

我想编写代码,找出从17的最短路径,在这种情况下,该路径将为1 -> 3 -> 7

这是我到目前为止所拥有的:

start = 1
lst = [[1, [2, 3]], [2, [4, 5]], [4, [6, 7]], [3, [7]]]

def getIt(start):
    for nest in lst:
        if start == lst[0]:
            return(nest[1])

allLists = []
loopCleaner = []
def travel(paths, totalList):
    if paths is not None:
        if 7 in paths:
            allLists.append(totalList)
        else:
            for path in paths:
                if path not in loopCleaner:
                    loopCleaner.append(path)
                    totalList.append(path)
                    travel(getIt(path), totalList)

print(travel(lst, []))

我正在尝试通过递归和循环的方式来进行此操作,但是它要么输出的路径太长,要么输出None。

我的逻辑:通过getIt获取所有可能的嵌套列表。

然后通过递归遍历所有对象,并在向下添加时继续添加到总计列表中,直到在其中一条路径中找到7。在这种情况下,我们结束并退出。如何以仅获得[1, 3, 7]的方式编码?

1 个答案:

答案 0 :(得分:0)

您可以将递归与生成器一起使用:

def paths(d, start, end, c = [], seen=[]):
  if end in d.get(start, []):
     yield c+[end]
  else:
     for i in filter(lambda x:x not in seen, d.get(start, [])):
        yield from paths(d, i, end, c = c+[i], seen=seen+[i])

data = [[1, [2, 3]], [2, [4, 5]], [4, [6, 7]], [3, [7]]]
print(min(list(paths(dict(data), 1, 7, c=[1])), key=len))

输出:

[1, 3, 7]