我有问题了解返回的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(数字-1)”和“斐波那契(数字-2)”是否同时处理?或者“斐波那契(数字-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(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,returning 1 + 0 Number is currently 4,returning 2 + 1 3
它仍然很复杂,但至少现在你可以看到函数正在做什么来计算你的数字.