No, you cannot set the return value of a function from outside the function. Instead, use a variable in the calling function.
For instance, here, you want to remember which nodes you visited. A set
is good for remembering a set of objects.
def explore(v):
visited.add(v)
for (v,w) in E:
if w not in visited:
explore(w)
A couple of cautions about this:
If you call it twice, everything will be seen as already visited, because the state is tracked in a global. That's similar to what you already have but may or may not be what you want. If you want to be able to iterate twice, you need to pass this down as a parameter, and preferably add a second function that starts the recursion:
def explore(v):
return explore_down(v, set())
def explore_down(v, visited):
visited.add(v)
for (v,w) in E:
if w not in visited:
explore(w)
Also, depending on what type v
and w
are, you may get an error that they're not hashable, for which see this question.