根据源目的地字典计算源路径

时间:2019-01-16 09:27:19

标签: python

我有一个输入字典-dict_input,目标为keys,源为values。一个目的地可以有一个或多个来源。

dict_input = {'C411':['C052'],'C052':['C001','C002'], 'C001':['9001'], 'C002':['9002']}

dict_input上方,终端目的地为C411,而初始来源为90019002。我正在尝试为终端目标C411提供源路径。预期输出为list-

[['C411', 'C052', 'C001', '9001'], ['C411', 'C052','C002', '9002']]

我有此代码:

def get_source(node, dict_input, source=[]):
    if node in dict_input:
        source.append(node)
        for i in dict_input[node]:
            if i != node:
                get_source(i, dict_input, source)
            else:
                source.append(node)
    else:
        source.append(node)
        return source
    return source

dict_input = {'C052':['C001','C002'], 'C411':['C052'], 'C001':['9001'], 'C002':['9002']} 

print(get_source('C411', dict_input, []))

输出是合并到一个列表中的两个源路径-

['C411', 'C052', 'C001', '9001', 'C002', '9002']

如何修改代码以获取每个源路径的单独列表?

1 个答案:

答案 0 :(得分:4)

  • 访问完一个节点后,不要忘记从当前路径pop
  • 如果遇到“叶子”(不是键的节点ID),请在输出列表中存储当前路径的副本
  • 提防损坏的数据,例如循环链接-有助于保持set个访问过的节点

上述示例的实现:

def get_source(root, dict_input):

    # output list
    path_list = []

    # current path
    cur_path = []

    # visited set
    visited = set()

    # internal recursive helper function
    def helper(node):
        cur_path.append(node)

        # normal node
        if node in dict_input:
            if not node in visited:
                visited.add(node)
                for child in dict_input[node]:
                    helper(child)

            # else: cycle detected, raise an exception?

        # leaf node
        else:
            # important: must be a copy of the current path
            path_list.append(list(cur_path))

        cur_path.pop()

    # call this helper function on the root node
    helper(root)

    return path_list

测试:

>>> dict_input = {'C411':['C052'],'C052':['C001','C002'], 'C001':['9001'], 'C002':['9002']}

>>> get_source('C411', dict_input)
[['C411', 'C052', 'C001', '9001'], ['C411', 'C052', 'C002', '9002']]