I had dataset like below:
A B
1 2
5 3
2 5
3
Below code gives me the following output:
def all_paths(table, root):
# convert table structure to adjacency list
children = {}
for node, child in table:
if child:
children[node] = children.setdefault(node, []) + [child]
# generator for iteration over all paths from a certain node
def recurse(path):
yield path
if path[-1] in children:
for child in children[path[-1]]: # recursive calls for all child nodes
yield from recurse(path + [child])
return recurse([root])
# Sample data in simple list format
table = [
[1, 2],
[5, 3],
[2, 5],
[2, 6],
[2, 4],
[6, 7],
]
# Output all paths from node 1
for path in all_paths(table, 1):
print(path)
Output:
[1]
[1, 2]
[1, 2, 5]
[1, 2, 5, 3]
[1, 2, 6]
[1, 2, 6, 7]
[1, 2, 4]
But what i want here is to print output in render tree format like below:
1
└── 2
|── 5
| └──3
|── 6
| └──7
└── 4
I know python library Anytree is useful here but I don't know how to implement this code. Any help would be highly appreciated.
Your current output
[[1], [1, 2], [1, 2, 5], [1, 2, 5, 3], [1, 2, 6], [1, 2, 6, 7], [1, 2, 4]]
is a flattened list. The first step is to fold it to a tree structure. Then you can render through it via a simple decorator. (code below were tested with Python 3.6.1)