这是一个更通用的编程/范例/算法问题,但我将使用python进行布局。
给出以下数据结构:
如何折叠此数据结构以获取起始元素的所有路径?
为了进一步说明问题,让我详细说明
c = {
'children': []
}
b = {
'children': [c]
}
a = {
'children': [b]
}
fold_from_start(a) => [[a, b, c]]
此函数应从a计算所有路径。如果我们像这样扩展前一个:
d = {
'children': []
}
b['children'] = [c, d]
fold_from_start(a) => [[a, b, c], [a, b, d]]
到目前为止,我已经使用递归构造提出了以下代码:
def fold_from_start(start, path, paths):
if not len(start['children']):
paths.append(path) # leaf element
else:
new_path = path.copy()
new_path.append(start)
for child in start['children']:
fold_from_start(child, new_path, paths)
可以这样称呼:
paths = []
fold_from_start(a, [a], paths)
不幸的是它产生了
[a, a, b]
[a, a, b]
我知道我以前曾在教科书中看到过这段代码,但是不幸的是我无法提出完成的方法。 我倾向于忽略的此功能中的明显问题是什么?
答案 0 :(得分:1)
只有几个小错误。这有效:
c = {
'name' : 'c',
'children': []
}
b = {
'name' : 'b',
'children': [c]
}
a = {
'name' : 'a',
'children': [b]
}
d = {
'name' : 'd',
'children': []
}
b['children'] = [c, d]
def fold_from_start(start, path, paths):
new_path = path.copy()
new_path.append(start['name'])
if len(start['children']) == 0:
paths.append(new_path) # leaf element
else:
for child in start['children']:
fold_from_start(child, new_path, paths)
paths=[]
fold_from_start(a, [], paths)
print(str(paths))
您还必须将叶子节点添加到当前路径。 但是由于您不想将其添加到调用方的路径变量中,因此请先复制。