查找未排序的d路径

2024-04-19 23:44:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据:

data = [
    {"start": "MIA", "end": "FCA"},
    {"start": "FCA", "end": "GVK"},
    {"start": "GVK", "end": "LSD"}
]

有了这些数据,我需要找到一条路径。在上述情况下,路径将是从MIAFCA,然后是FCAGVK,最后是GVKLSD。路径永远不会有分支,也不会返回到已经通过的点,没有循环。作为输出,我只需要得到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"])。我觉得有点乱了。你知道吗


Tags: 数据path路径元素dataifcounterfind
1条回答
网友
1楼 · 发布于 2024-04-19 23:44:51

以下递归函数将完成此任务:

data = [
    {"start": "FCA", "end": "GVK"},
    {"start": "MIA", "end": "FCA"},
    {"start": "GVK", "end": "LSD"}
]

def find_path(data, start='', result=[]):
    l = data.copy()
    for d in data:
        if d['start'] == start:
            result.append(d['end'])
            l.remove(d)
            find_path(l, result[-1], result)
    return result

print(find_path(data, 'MIA'))

输出:

['FCA', 'GVK', 'LSD']

相关问题 更多 >