Python conditional operator 'if else' is not equal to 'and'

I think below the result of the two functions will be the same, but it is not.

def fib2(n):
  return n and n < 2 or fib2(n-1) + fib2(n-2)

def fib3(m):
  return m if m < 2 else fib3(m-1) + fib3(m-2)

When the value of the argument is 4, the output of fib2 is 7, the output of fib3 is 3. Why does this happen? I do not know about that. My Python version is 2.7.9 and os is osX 10.11.1

+4
source share
1 answer

I tried to be more detailed and write your functions as follows:

def fib2(n):
    ret = n and n < 2 or fib2(n-1) + fib2(n-2)
    print "fib2({}) = {}".format(n, ret)
    return ret

print fib2(4)

def fib3(m):
    ret = m if m < 2 else fib3(m-1) + fib3(m-2)
    print "fib3({}) = {}".format(m, ret)
    return ret

print fib3(4)

, fib2 , . fib3 . , ! fib3 (1000), . 0 1 , .

, #n :

def fib4(n):
    a = 0
    b = 1
    for i in range(1, n + 1):
        a, b = (b, a + b)
    return a

print fib4(0)
print fib4(1)
print fib4(2)
print fib4(3)
print fib4(4)
print fib4(1000)

, n==1000.

+1

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


All Articles