Reputation: 11
I'm trying to solve "is_even" and "is_odd" function in terms of the other with recursion. I don't understand HOW this function as written ever evaluates to False, or how anything that isn't 0 ever evaluates to True. I double-checked it in teamtreehouse.com workspaces to make sure it works at all, but I can't figure out HOW it works.
I understand that it's decrementing through recursion, but I don't understand how is_odd(x) works. If is_odd(x) just negates everything in is_even, why don't all numbers evaluate to True? Or False?
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
# Does this negate the function of is_even(x)?
# Does that negating mean returning False, or sending to else block?
# If the negating does automatically sends to the else block
# After we get here, do we ever land at True in is_even(x)?
# If not, how do we ever land at False?
print(is_even(1))
print(is_even(2))
print(is_even(3))
Upvotes: 0
Views: 1170
Reputation: 1618
What Sasha said is correct, however it does not fully illustrate the recursive call-stack.
x = 3
is_even(3):
return is_odd(2)
call is_even(2)
return is_odd(1)
call is_even(1)
return is_odd(0)
return is_even(0): True
return not True: False
return not False: True
return not True: False
Upvotes: 0
Reputation: 126
Let's take an example of the function is_even(1). What happens?
(1)
Let's now take an example of is_even(2). What happens?
(2)
Now with is_even(3)
(3)
To your questions again:
Yes: not is_even(x) negates the result of is_even(x), as you saw in my examples.
No. If the function is_even(x) returns True, not True returns False. If the function is_even(x) returns False, not False returns True. So it negates the result of is_even(x)
Since you always decrease the argument with (x-1), you will always eventually get to x=0, as you also saw in my examples.
Upvotes: 0
Reputation: 1153
x = 0
is_even: True
x = 1
is_even:
is_odd(0):
is_even(0): True
not True: False
False
x = 2
is_even:
is_odd(1):
is_even(1): False
not False: True
True
x = 3
is_even:
is_odd(2):
is_even(2): True
not True: False
False
Upvotes: 2