0
someone please explain this program..how it works
def is_even(x): if x == 0: print (": ", end="") return True else: print ("(is_even " + str(x) + ")", end="") return is_odd(x-1) def is_odd(x): print ("(not is_even " + str(x) + ")", end="") return not is_even(x) print(is_odd(2)) print(is_even(2))
2 Answers
+ 1
We can better understand your program if we simplify the code
def is_even(x):
if x == 0: return True
return not is_even(x-1)
We can see that for example is_even(5) will recurse through
NOT is_even(4) -> NOT is_even(3) -> NOT is_even(2) -> NOT is_even(1) -> NOT is_even(0)
Starting from 0 and going in the opposite direction:
False (4) <- True (3) <- False (2) <- True (1) <- False (0)
So we can see that, if the number of recursions is odd as in case of 5 and all odd numbers, is_even() will return False; if the number of recursions is even as in case of 2 and all even numbers, is_even will return True