0

I want to set the default value of a boolean function to be False and want to change it to True only for certain values of the input in between the code. Is there a way to do it?

I'm trying to write a simple DFS search code. The code I'm using is this:

def visited(v):
    return False
def explore(v):
    visited(v) = True
    for (v,w) in E:
        if not visited(w):
            explore(w)
dexteran
  • 95
  • 8

3 Answers3

1

A function is probably the wrong tool here. Instead, try a set:

def explore(v, visited=set()):
    visited.add(v)
    for (v,w) in E:
        if w not in visited:
            explore(w)

I'm using a sometimes unintuitive behavior of default arguments in Python for this example code because it's convenient, but you could also use a different way of maintaining a shared set, such as a wrapper function that initializes a blank set and then calls a recursive helper function. (That would let you explore multiple times by resetting the set each time.)

Amber
  • 446,318
  • 77
  • 595
  • 531
0

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.

Community
  • 1
  • 1
poolie
  • 8,454
  • 1
  • 43
  • 69
0

Assuming you have a myfunc function returning a boolean, that you want to modify the behaviour:

_myfunc = myfunc

def myfunc(*args):
    if some_condition:
        _myfunc(*args)
    else:
        return False

This way, you will trigger the actual function only in wished cases.

This solution overwrites the original name, but you are not obliged to do so.

Right leg
  • 13,581
  • 5
  • 36
  • 68