Skip to content

Instantly share code, notes, and snippets.

@azalea
Created August 7, 2012 23:04
Show Gist options
  • Save azalea/3290375 to your computer and use it in GitHub Desktop.
Save azalea/3290375 to your computer and use it in GitHub Desktop.
Bug of defaultdict?
import collections
def dfs(G, s, path=[]):
global explored
explored.add(s)
path.append(s)
for v in G[s]:
if v not in path:
path = dfs(G, v, path)
return path
def dfsloop(G):
for v in G: # No error if "for v in G.keys():"
if v not in explored:
dfs(G, v)
G = collections.defaultdict(list)
G[1] = [9, 8, 2, 0, 6]
G[2] = [9, 0, 8]
G[3] = [1, 6, 8]
G[6] = [8, 9, 2, 0]
G[7] = [6, 1, 2, 3, 9]
G[8] = [0, 9]
G[9] = [0]
# "for v in G" and "for v in G.keys()" should be the same
print 'for v in G:'
for v in G:
print v
print 'for v in G.keys():'
for v in G.keys():
print v
explored = set()
dfsloop(G)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment