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))
It is difficult to explain. I ran this in VSCode Debug mode and understood what exactly is happening. If you don't have VSCode, try doing a dry run on paper with value 1 and then with 2.
I'll try explainig. So we are reducing x by 1 and calling each function alternatively, and line 3 will return True
when x reaches zero. And each method call basically just negates the other method's output.
So, it's all about how many times the True is flipped to False and then back to True.
In case of even number in is_even()
method:
True -> False -> True (RUNS ODD NUMBER OF TIMES)
In case of odd number in is_even()
method:
True -> False -> True -> False (RUNS EVEN NUMBER OF TIMES)
is_even
: if the argument is 0 returns True otherwise it returns the same output as is_odd(x-1)
is_odd
: returns the opposite of whatever comes out when it passes it to is_even
It's always best to look at the small inputs.
is_even(0)
Out: True
is_odd(0)
Out: False
is_even(1)
Out: False
is_odd(1)
Out: True
is_even(2)
Out: True
is_odd(2)
Out: False
hopefully that helps...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.