How to get all combinations (listed) from a given dictionary, in python ?
My Dictionary Input :
node_data = {
"1":["2","3","4","5"],#1
"2":["7","8"],#2
"3":["6"],#3
"4":[],#4
"5":[],#5
"6":["11"],#6
"7":[],#7
"8":["9","10",],#8
"9":["12"],#9
"10":[],#10
"11":["13"],#11
"12":[],#12
"13":["14"],#13
"14":[]#14
}
Desidered output (sort by the longest node):
["1","3","6","11","13","14"]
["1","2","8","9","12"]
["1","2","8","10"]
["1","2","7"]
["1","4"]
["1","5"]
CodePudding user response:
I did something like this and it seems to work:
def recurse(current, nodes, path, all_path):
path.append(current)
if nodes[current]:
for child in nodes[current]:
recurse(child, nodes, path.copy(), all_path)
else:
all_path.append(path)
return all_path
if __name__ == '__main__':
node_data = {
"1":["2","3","4","5"],#1
"2":["7","8"],#2
"3":["6"],#3
"4":[],#4
"5":[],#5
"6":["11"],#6
"7":[],#7
"8":["9","10",],#8
"9":["12"],#9
"10":[],#10
"11":["13"],#11
"12":[],#12
"13":["14"],#13
"14":[]#14
}
toto = recurse("1", node_data, [], [])
toto.sort(key=len, reverse=True)
print(toto)
Hope it'll help you