我有一个描述树的词典列表,例如:
data
每一行都是一个包含下一个分支的dict。第一行中dict的键是根,后续行包含下一个可能的节点。
我想创建一个包含所有可能路径的[列表]列表,例如:
ByteBuffer
虽然有很多SO示例使用递归/生成器用于二叉树,或非二进制[但使用嵌套字典],但在上面描述树的情况下,我找不到合适的方法来执行此操作。此外,使用networkx和all_simple_paths不会保留树的分层特性,因此会因此应用程序而中断。
想法?
答案 0 :(得分:1)
以下递归生成器函数将执行:
def paths(tree, node=None):
if not tree or (node and node not in tree[0]):
yield [node] if node else []
return
d = tree[0]
nodes = [node] if node else d.keys()
for node in nodes:
for child in d[node]:
for path in paths(tree[1:], node=child):
yield [node] + path
>>> list(paths(tree))
[[(1, 0), (1, 0), (2, 0), (1, 0)],
[(1, 0), (1, 0), (2, 0), (1, 3)],
[(1, 0), (1, 1), (2, 1), (1, 1)],
[(1, 0), (1, 1), (2, 1), (1, 4)],
[(1, 0), (1, 2), (2, 2), (1, 2)],
[(1, 0), (1, 2), (2, 2), (1, 5)],
[(1, 3), (1, 3), (2, 0), (1, 0)],
[(1, 3), (1, 3), (2, 0), (1, 3)],
[(1, 3), (1, 4), (2, 1), (1, 1)],
[(1, 3), (1, 4), (2, 1), (1, 4)],
[(1, 3), (1, 5), (2, 2), (1, 2)],
[(1, 3), (1, 5), (2, 2), (1, 5)]]