Home > Mobile >  recursive tree search create array of all paths
recursive tree search create array of all paths

Time:11-26

I have a dict {child, parent}

mydict = {'1': '0',
 '2': '0',
 '3': '1',
 '4': '3',
 '5': '3',
 '6': '2',
 '7': '6',
 '8': '7'  }

I don't know how many levels of grandchildren there are. I need to end up with a structure that has all unique parent,child,grandchild paths.

path1:[0,1,3,4], path2:[0,1,3,5], path3:[0,2,6,7,8]

I have written function that traverses the entire tree and print each value

def getvalues(x):
    xlist = [(i,j) for i,j in mydict.items() if j == x]
    for y in xlist:
        print(y[1], y[0])
        getvalues(y[0])


getvalues('0')
0 1
1 3
3 4
3 5
0 2
2 6
6 7
7 8

But I am at a loss of how to store the interim values at each level and get them into the array format i need

path1:[0,1,3,4], path2:[0,1,3,5], path3:[0,2,6,7,8]

CodePudding user response:

Try:

mydict = {
    "1": "0",
    "2": "0",
    "3": "1",
    "4": "3",
    "5": "3",
    "6": "2",
    "7": "6",
    "8": "7",
}


def get_all_paths(dct, start="0", curr_path=None):
    if curr_path is None:
        curr_path = [start]

    next_values = dct.get(start)
    if not next_values:
        yield curr_path
        return

    for v in next_values:
        yield from get_all_paths(dct, v, curr_path   [v])


inv_dict = {}
for k, v in mydict.items():
    inv_dict.setdefault(v, []).append(k)


out = {f"path{i}": path for i, path in enumerate(get_all_paths(inv_dict), 1)}
print(out)

Prints:

{
    "path1": ["0", "1", "3", "4"],
    "path2": ["0", "1", "3", "5"],
    "path3": ["0", "2", "6", "7", "8"],
}
  • Related