In the function below, when I use path = path + [start]
then I will get the result ['A', 'B', 'E']
but when I use path += [start]
then I will get the result ['A', 'B', 'D', 'E']
. Why?
My code:
graph1 = {'A':['B','C'],
'B':['A','D','E'],
'C':['A','F'],
'D':['B'],
'E':['B','F'],
'F':['C','E']}
def find_path(graph,start,end,path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph,node,end,path)
if newpath:
return newpath
return None
print(find_path(graph1,'A','E'))