Program to generate all the possible paths from one node to the other

Question:

I wanted to generate all the possible paths from one node to the other with this program:

graph = { "a" : ["b","c"],
      "b" : ["a", "d"],
      "c" : ["a", "d"],
      "d" : ["e"],
      "e" : ["b"]
     }

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    paths = []
    for node in graph[start]:
        if node not in path:
            newpaths = find_all_paths(graph, node, end, path)
        for newpath in newpaths:
            paths.append(newpath)
    return paths


print(find_all_paths(graph, "b","e"))

But unfortunately I get the Error:
UnboundLocalError: local variable ‘newpaths’ referenced before assignment

Can anyone help me?

Asked By: SumSum

||

Answers:

I might be wrong but this seems clear. In your function find_all_paths(), in your for loop, you are calling newpath before it exist. I would suggest to declare newpath here

def find_all_paths(graph, start, end, path=[]):
      newpaths = []
      path = path + [start]

It should work

EDIT:
As DarryIG suggest, indent 2nd for loop is also working and probably safer than my solution

Answered By: Ludmino
graph = { "a" : ["b","c"],
      "b" : ["a", "d"],
      "c" : ["a", "d"],
      "d" : ["e"],
      "e" : ["b"]
     }

path =  []
def find_all_paths(graph, start, end, path):
    global newpaths 
    path = path + [start]
    if start == end:
        return [path]
    paths = []
    for node in graph[start]:
        if node not in path:
            newpaths = find_all_paths(graph, node, end, path)
            for x in newpaths:
                paths.append(x)
    return paths

there you go, you need to set the variable as global before use it.

Answered By: Lucas Noleto
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.