I'm writing a simple DFS algorithm, but when I run the function, it seems like the argument I'm passing in is carried on into the next call. I feel somewhat comfortable with how scoping in Python works, but I've never really considered how scoping works for arguments. Can someone explain how this scoping issue is occurring?
The only reason I can think of is that the default value I give path isn't created anew every time I run the function...?
Graph Object:
graph = {
1: [2,8,12],
2: [3,7],
3: [4,5,6],
8: [9],
9: [10,11],
12: [13],
13: [14]
}
DFS Algorithm:
def dfs_dict(graph, curr, val, path=[]):
path.append(curr)
print "Path: " + str(path)
if curr == val:
return path
else:
if curr in graph: # not a disconnected node/leaf
for child in graph[curr]:
if child not in path:
tmp = dfs_dict(graph, child, val, path)
if tmp:
return tmp
How I'm running DFS:
if __name__ == '__main__':
print dfs_dict(graph, 1, 13)
print dfs_dict(graph, 1, 7)
OUTPUT:
Path: [1]
Path: [1, 2]
Path: [1, 2, 3]
Path: [1, 2, 3, 4]
Path: [1, 2, 3, 4, 5]
Path: [1, 2, 3, 4, 5, 6]
Path: [1, 2, 3, 4, 5, 6, 7]
Path: [1, 2, 3, 4, 5, 6, 7, 8]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1]
None