0
How to make it direct recursion?
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))
1 Answer
+ 1
It is very inefficient to check is_even and is_odd that way because those problems can be done in O(1) time with less code like this:
def is_even(x):
return x % 2 == 0
def is_odd(x):
return x % 2 == 1
Let's solve using direct recursion anyway, though.
def is_even(x):
if x == 0:
return True
else:
return not is_even(x - 1)
def is_odd(x):
if x == 0:
return False
else:
return not is_odd(x - 1)
# test them.
for i in range(10):
print('Is %d odd? ' % i)
print(is_odd(i))
print('Is %d even? ' % i)
print(is_even(i))