I have this chunk of pythonic code that I've been having trouble understanding:
paths = [[end]]
while paths and paths[0][0] != start:
paths = [[parent] + path for path in paths for parent in childToParents[path[0]]]
where childToParents is:
defaultdict(<class 'set'>, {'cog': {'log', 'dog'},
'dog': {'dot'},
'dot': {'hot'},
'hit': None,
'hot': {'hit'},
'log': {'lot'},
'lot': {'hot'}})
end is "cog", start is "hit". The expected output of paths is:
[["hit","hot","lot","log","cog"],["hit","hot","dot","dog","cog"]]
I have tried multiple variations of a double for loop. One such attempt is:
paths=[[end]]
while paths and paths[0][0] != start:
for i in xrange(len(paths)):
for parent in childToParents[paths[i][0]]:
paths[i] = [parent] + paths[i]
But this only gives me:
[["hit","hot","dot","dog","log","cog"]]
How can I translate the code to a standard double for loop?
whilewith afor, just usefor _ in count(): if not <condition>: breakbut this is just syntactic quibbling... In this specific case it seems like the code is doing something like visiting a graph or following a set of paths in a graph. You generally cannot predict how many iterations you'll do since it depends on the graph structure.