Home > Software engineering >  Why this dual recursive code works in python and how?
Why this dual recursive code works in python and how?

Time:09-02

This code gives exactly what is says but how and why?

To my understanding, for instance the is_odd function if called with any value, the value will diminish into zero and will return True in the is_even() section and so will become False in is_odd() in turn. So every is_odd check supposed to become False but it's not, it just works on every odd/even check, why and how?

#!/bin/python

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(2))
print(is_even(2))
print(is_odd(3))
print(is_even(3))

Output:

False
True
True
False

CodePudding user response:

Note that is_even does not always return True but can also return is_odd(n-1), which in turn return not is_even(n-1), and so on.

Example for is_odd(3):

is_odd(3)
not is_even(3)
not is_odd(2)
not not is_even(2)
not not is_odd(1)
not not not is_even(1)
not not not is_odd(0)
not not not not is_even(0)
not not not not True
not not not False
not not True
not False
True

In general, you get a cascade of N negations for an even number, or N 1 negations for an odd number, and if the number of those negations is even, the result is True.

  • Related