我无法理解 return fibonacci( number-1 ) + fibonacci( number-2 )
在以下程序中的作用:
import sys
def fibonacci( number ):
if( number <= 2 ):
return 1
else:
return fibonacci( number-1 ) + fibonacci( number-2 )
问题是我无法想象这条线是如何工作的:
return fibonacci( number-1 ) + fibonacci( number-2 )
是否同时处理“fibonacci(number-1)”和“fibonacci(number-2)”?或者“fibonacci(number-1)”是第一个要处理的,然后是第二个?
我只看到处理它们最终会返回 '1' 所以我希望看到的最后一个结果是 '1 + 1' = '2'
如果有人可以详细解释其计算过程,我将不胜感激。
我认为这是一个非常新的问题,但我无法真正了解其过程。
最佳答案
你为什么不做这样的事情:
>>> def fibonacci(number):
... if number < 2:
... return number
... print "Number is currently %d, getting fibonacci(%d)" % (number, number - 1)
... minus_one = fibonacci(number-1)
... print "Number is currently %d, just got fibonacci(%d), now getting fibonacci(%d)" % (number, number - 1, number - 2)
... minus_two = fibonacci(number-2)
... print "Number is currently %d, returning %d + %d" % (number, minus_one, minus_two)
... return minus_one + minus_two
因此,当您调用
fibonacci
时,您会得到如下信息:>>> fibonacci(4)
Number is currently 4, getting fibonacci(3)
Number is currently 3, getting fibonacci(2)
Number is currently 2, getting fibonacci(1)
Number is currently 2, just got fibonacci(1), now getting fibonacci(0)
Number is currently 2, returning 1 + 0
Number is currently 3, just got fibonacci(2), now getting fibonacci(1)
Number is currently 3, returning 1 + 1
Number is currently 4, just got fibonacci(3), now getting fibonacci(2)
Number is currently 2, getting fibonacci(1)
Number is currently 2, just got fibonacci(1), now getting fibonacci(0)
Number is currently 2, returning 1 + 0
Number is currently 4, returning 2 + 1
3
它仍然很复杂,但至少现在您可以看到该函数正在做什么来计算您的数字。
关于python - 这个程序中的 "return fibonacci... "是怎么回事?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11181047/