0

Trying to refresh my DSA knowledge in python, so I am writing a Graph class. While implementing a find_all_paths method I run into something that I am not quite understanding. I'll start by posting the code:

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if not graph.has_key(start):
        return []
    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

     graph = {'A': ['B', 'C'],
         'B': ['C', 'D'],
         'C': ['D'],
         'D': ['C'],
         'E': ['F'],
         'F': ['C']}

          print(find_all_paths(graph, 'A', 'D'))

The first line in the method adds the starting node to our path list. I initially had it written as path += [start] instead of path = path + [start]. The first one returns the desired output while the second doesn't. In other words: - When using path += [start] i get [['A', 'B', 'C', 'D']] as an output. - When using path = path + [start] i get [['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']] as an ouptut. Any insights as to why would be greatly appreciated. Thanks in advance.

tjbadr
  • 18
  • 4
  • 1
    because `path = path + [start]` creates a new list, whereas `path += [start]` modifies the existing list – Hamms Jun 14 '16 at 16:15
  • 3
    Never use mutable default arguments: http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Alicia Garcia-Raboso Jun 14 '16 at 16:16
  • when I use `path =+ [start]`, there's an error: **TypeError: bad operand type for unary +: 'list'** – Hui-Yu Lee Jun 14 '16 at 16:17
  • 2
    In addition you have a mutable default argument. If you change it, the default will change, except you overwrite the name with `path =...` inside the function. – Klaus D. Jun 14 '16 at 16:22
  • That makes sense. Thanks for the quick responses! – tjbadr Jun 14 '16 at 16:34

0 Answers0