0
Return
Hello, I struggled with this, can someone help me understand how to view this return*? def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_odd(17)) print(is_even(23))
6 Answers
+ 1
Letâs start with return not is even (x) please
0
Hi!
It recursively negates the result of the result of the result...of (x - 1) == 0, until x = 0.
Example with 3 (odd):
3 == 0 [True] [False] -> False -> not (x - 1) ->
2 == 0 [True] [False] -> not False -> (not) not (x - 1) ->
1 == 0 [True] [False] -> not not False -> (not, not) not (x - 1) ->
0 == 0 [True] [False] -> not not not True -> False
Actually, there is no need of is_odd(x) function.
def is_even(x):
if x == 0:
return True
return not is_even(x - 1)
print(is_even(17)) # False (odd)
print(is_even(18)) # True (even)
0
Thanks guys,
I am still struggling with this, is there an easier example please?
0
I think that it will be easier for you to understand it, if you remove the is_odd function, like in my example.
It works the same way, without it.
not is_even means that if x = 0, then you return True in the is_even function. But since there is 'not' in front of it, it becomes False.
Assume that you call is_even(17), then 17 == 0 is False, so it returns is_odd(17 - 1), which returns not is_even, which checks 16 == 0 (False), so again it returns is_odd(x - 1), which returns not is_even(15). And here is the tricky part. Since you are going deeper in the recursion tree, while x > 0, the not operator is stacked (you got always not not not not not) and when x = 0 you return True, but it might be False in the end:
x = 3
3 == 0 -> returns is_odd(x - 1) -> returns not is_even(2) ->
2 == 0 -> returns is_odd(x - 1) ->
returns not is_even(1) ->
1 == 0 -> returns is_odd(x - 1) ->
returns not is_even(0) ->
0 == 0 -> returns True.
Now count how many times you call not is_even(x). 3 times, right?
So, not not not True = False (3 is odd)
1. not True = False
2. not False = True
3. not True = False
Hope it's more clear now.
0
Thanks a lot Boris, I believe I get it now. Thanks for patiently explaining!!!
0
I'm glad if helped.
Perhaps this approach is just for recursion demo. It works for 0 <= x <= 997.