Search code examples
pythongraphnodes

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


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?


Solution

  • 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