我有以下数据:
data = [
{"start": "MIA", "end": "FCA"},
{"start": "FCA", "end": "GVK"},
{"start": "GVK", "end": "LSD"}
]
有了这些数据,我需要找到一条路径。在上述情况下,路径将是从MIA
到FCA
,然后是FCA
到GVK
,最后是GVK
到LSD
。路径永远不会有分支,也不会返回到已经通过的点,没有循环。作为输出,我只需要得到data
数组的每个元素的"end"
点:["FCA", "GVK", "LSD"]
所以,这就是我所尝试的:
def find_path(connections, counter, data):
if connections[-1] == data[counter]["start"]:
connections.append(data[counter]["end"])
if len(connections) == len(data):
return connections
return find_path(connections, counter+1, data)
它只会因为data
被排序而起作用。但是当我改变data
就像这样:
data = [
{"start": "FCA", "end": "GVK"},
{"start": "MIA", "end": "FCA"},
{"start": "GVK", "end": "LSD"}
]
它失败了。你知道吗
问题:实现这一目标的最佳方法是什么?你知道吗
我考虑过在函数到达数据末尾时重置函数顶部的counter
,但是有了这个,我就不得不在这里的connections
索引处打折:if connections[-1] == data[counter]["start"]:
,并在这里的不同位置附加data
元素:connections.append(data[counter]["end"])
。我觉得有点乱了。你知道吗
以下递归函数将完成此任务:
输出:
相关问题 更多 >
编程相关推荐