Python conditional operator 'if else' not equal 'and or' [duplicate]

孤街醉人 提交于 2019-12-12 12:17:42

问题


I think below two function result will be 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 argument value is 4, fib2's output is 7, fib3's output is 3. Why this situation happen? I don't know about this.
My Python version is 2.7.9 and os is osX 10.11.1


回答1:


I tried to be more verbose and write your functions like this:

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)

It appears that fib2 tries to add boolean values to numbers, and that's why it's not correct. fib3 handles only numbers and is correct. But notice that it's not a recommended way to calculate Fibonacci numbers! If you try fib3(1000) it will run infinitely. It's better to start from 0 and 1 upwards, and not use recursion to calculate Fibonacci numbers.

I wrote a short function that calculates Fibonacci number #n for you:

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)

Notice it also works for n==1000.



来源:https://stackoverflow.com/questions/33780600/python-conditional-operator-if-else-not-equal-and-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!