Home > Net >  please help me to understand this code of python recursion?
please help me to understand this code of python recursion?

Time:08-06

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))

CodePudding user response:

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)

CodePudding user response:

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.


Sequence A

is_even(0)

  • in <- 0
  • returns True -> True

Out: True


Sequence B

is_odd(0)

  • in <- 0
  • Sequence A -> True
  • odd returns opposite -> False

Out: False


Sequence C

is_even(1)

  • in <- 1
  • Sequence B -> False
  • even returns the same -> False

Out: False


Sequence D

is_odd(1)

  • in <- 1
  • Sequence C -> False
  • odd returns opposite -> True

Out: True


Sequence E

is_even(2)

  • in <- 2
  • Sequence D -> True
  • even returns the same -> True

Out: True


Sequence F

is_odd(2)

  • in <- 2
  • Sequence E -> True
  • odd returns the opposite -> False

Out: False

hopefully that helps...

  • Related