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.