Recursive check odd or even

In this code:

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

I continue this in my head and wonder how it works. It seems to me that in the end xto is_even(x)be returned Trueeach time. However, when I run the code, it works fine and returns Trueand Falseappropriate. Can someone explain how this happens?

I understand the basic concept of recursion and fully understand how the famous factorial example works. However, it’s hard for me to hug my head.

Feeling unulocal right now ...

+4
source share
5 answers

It always helps to decompose the repetition relation until you find its base case.

is_even(2) => return is_odd(1) 
           => return not is_even(1) 
           => return not is_odd(0)
           => return not not is_even(0)
           => return not not True
           => return True            ---- (1)

is_odd(2) => return not is_even(2) 
          => return not True       [from (1)] 
          => return False

, , is_even(n) [not not not ... n times] True, is_odd(n) [not not not ... n - 1 times] True. , not , , n (aha!). , , ,

n % 2 == 0
+9

print, , :

from __future__ import print_function

def is_even(x):
    if x == 0:
        print('True')
        return True
    else:
        return is_odd(x-1)

def is_odd(x):
    print('not', end=' ')
    return not is_even(x)

>>> is_even(5)
not not not not not True
False
>>> is_odd(5)
not not not not not not True
True
+5

, print :

def is_even(x):
    print('check if {} is even'.format(x))
    if x == 0:
        return True
    else:
        return is_odd(x-1)

def is_odd(x):
    print('check if {} is odd'.format(x))
    return not is_even(x)

:

>>> print(is_even(2))
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
True

>>> print(is_odd(2))
check if 2 is odd
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
False

, 0. , not is_odd. not, True, False.

+3

; is_even.

, , 0.

. - is_even(0) is_odd(0). - . - is_odd, , , , .

- : , , - , return is_odd(x-1).


: True, is_even. x, x - , .

, ( is_odd):

def is_even (x):
    res = True
    while x:
        res = not res
        x -= 1
    return res
+2

, , , , , " ". , is_odd, . True , nots, , nots , , false.

+1

Source: https://habr.com/ru/post/1678742/


All Articles