我有一个输入字典-dict_input
,目标为keys
,源为values
。一个目的地可以有一个或多个来源。
dict_input = {'C411':['C052'],'C052':['C001','C002'], 'C001':['9001'], 'C002':['9002']}
在dict_input
上方,终端目的地为C411
,而初始来源为9001
和9002
。我正在尝试为终端目标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']
如何修改代码以获取每个源路径的单独列表?
答案 0 :(得分:4)
pop
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']]