In this code:
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_even(2))
print(is_odd(2))
I keep going through this in my head and wondering how it's working. It seems to me that eventually x
in is_even(x)
will return True
every time. However, when I run the code, it works perfectly fine and returns True
and False
appropriately. Can someone explain how that's happening?
I understand the basic concept of recursion and fully understand how the famous factorial example works. However, this one is hard for me to wrap my head around.
Feeling inept right now...
It always helps to decompose a recurrence relation till you find its base case.
is_even(2) => return is_odd(1)
=> return not is_even(1)
=> return not is_odd(0)
=> return not not is_even(0)
=> return not not True
=> return True ---- (1)
is_odd(2) => return not is_even(2)
=> return not True [from (1)]
=> return False
In general, from your recurrence functions, it is easy to observe that is_even(n)
will return [not not not ... n times] True
, while is_odd(n)
will return [not not not ... n - 1 times] True
. So the number of not
s and hence the final expression depend on n
(aha!). Well, that's certainly a roundabout way of asking whether
n % 2 == 0
Add a couple of print
statements and you will see what it is doing:
from __future__ import print_function
def is_even(x):
if x == 0:
print('True')
return True
else:
return is_odd(x-1)
def is_odd(x):
print('not', end=' ')
return not is_even(x)
>>> is_even(5)
not not not not not True
False
>>> is_odd(5)
not not not not not not True
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With