1

The Setup:

I have the following generator function:

def get_paths(ug, s, t, path=[], visited=set([])):
    if s == t: yield path

    visited.add(s)
    for n in ug[s]:
        if n in visited: continue
        yield from get_paths(ug, n, t, path + [n], visited)
    visited.remove(s)

It's generating all paths from s to t, on the undirected graph ug.

The graph is just an adjacency list in the form of a dictionary where ug[v] = [w1, w2, ..., wn] where there is an edge between v and each wi

The Problem:

The function works. If I iterate over it for some s, and t it will indeed generate all paths from s to t. However, something bizarre is happening when I do the following in a jupyter notebook cell:

for path in get_paths(udgraph, u, v):
    p = [n for n in path]
    print(p)
    break

print("\n")

for path in get_paths(udgraph, u, v):
    q = [n for n in path]
    print(q)

Both function calls are for the same u, and v. But here's the output:

[ni, nj, nk]


[na, nb]

As though the two separate function calls are coupled, when I break out of the first loop, the second one outputs only 1 path as well! This is the same path which would have been printed in the first loop had I not break'd out of it.

On the other hand, if I didn't break, then both loops would show all paths.

Another odd thing is that I have the generator function defined in the cell above the one I run it. If I'm iterating over the generator and I break early, I have to rerun the cell where the function is defined before it actually resets in the cell where it's called.

I'm not sure what's happening here. Can someone help me understand why this is happening? I suspect it has something to do with the end of the generator function, but I'm not sure.

Silver
  • 1,327
  • 12
  • 24

0 Answers0