I'm currently working with graph traversal. find_path with path incremented
like path = path + [start] returns [30, 3, 5, 8], whereas find_path2 with path
incremented like path +=[start] returns a list with every value find_path2 has
already traversed, [30, 3, 4, 0, 1, 2, 5, 8].
I'm guessing += acts like the append method where as path = path + [start]
does a reassignment?
Can someone explain the difference between path +=[start]
and path = path + [start]
def find_path2(graph, start, end, path=[]):
path += [start]
if start == end:
return path
if not start in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path2(graph, node, end, path)
if newpath: return newpath
return None
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not start 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
graph = {
0: [],
1: [],
2: [],
3: [4,2,5],
4: [0,1],
5:[8],
10:[5,6],
6:[],
30:[3]
}
print find_path(graph,30,8) #[30, 3, 5, 8]
print find_path2(graph,30,8) #[30, 3, 4, 0, 1, 2, 5, 8]