How can I return a truth value to the "base function" in recursion?
Question:
My function looks like this:
def func(x):
for i in range(x+1 to x+10):
if (condition):
return True
else:
func(i)
return False
Here, when we return True or False, the return value of the previous recursive call is not affected.
I want to do: if a recursive function returns True, the "base case function" should also return True immediately.
A workaround I’ve found is using a nonlocal variable:
var = False
def func(x):
nonlocal var
for i in range(x+1 to x+10):
if (condition):
var = True
else:
func(i)
return var
But is there a nicer way to do the same?
Answers:
It’s just this.
def func(x):
for i in range(x+1 to x+10):
if (condition):
return True
elif func(i):
return True
return False
Do use the return value of func(i)
as a boolean value.
My function looks like this:
def func(x):
for i in range(x+1 to x+10):
if (condition):
return True
else:
func(i)
return False
Here, when we return True or False, the return value of the previous recursive call is not affected.
I want to do: if a recursive function returns True, the "base case function" should also return True immediately.
A workaround I’ve found is using a nonlocal variable:
var = False
def func(x):
nonlocal var
for i in range(x+1 to x+10):
if (condition):
var = True
else:
func(i)
return var
But is there a nicer way to do the same?
It’s just this.
def func(x):
for i in range(x+1 to x+10):
if (condition):
return True
elif func(i):
return True
return False
Do use the return value of func(i)
as a boolean value.