I need to find the longest path to a given target. The data is a dictionary of ids with the value being a list of all ids that point to that id. Also worth noting that each Id can only point to one other id.
I tried to write a recursive function that will go through each possible path, and store each unique path option to another list, from which I will find the longest path.
def create(main, vec, id):
if (id not in INFO):
return(main, vec, id)
else:
for source in INFO[id]:
vec.append(source)
main.append(vec)
main, vec, id = create(main, vec, source)
return main,vec,id
and longest function
def longest(main):
longest = 0
long_list = 0
for list in main:
if len(list) > longest:
long_list = list
longest = len(list)
return long_list
when doing
INFO = {
'D4': ['B2','B6'],
'B6': ['D3'],
'D3': ['F1','A2'],
'A2': ['G8'],
'A1': ['C3'],
'B2': ['E3','A1']}
main, vec, id = create([],[],'D4')
print(longest(main))
I get main to have paths that stack on top of eachother. How would I fix the code so the paths don't stack. I hope to get main to look something like
[['B2'],
['B2','E3'],
['B2','A1'],
['B2','A1','C3'],
['B6'],
['B6','D3'],
['B6','D3','F1'],
['B6','D3','A2'],
['B6','D3','A2','G8']]
EDIT:
Changed line main, vec, id = create(main,[],'D4')
to main, vec, id = create([],[],'D4')
to clarify that main
is a list of lists.