我以为我理解递归函数,但意识到我实际上并不理解引擎盖下发生的事情
运行此 Python 代码来生成斐波那契数列,给出预期值
def fib(k):
result = 0
if(k > 0):
result = k + fib(k - 1)
print(f'after call k is {k} and result is {result}')
else:
print()
return result
#return k
print("Recursion Example Results")
fib(6)
这就是它返回的内容:
Recursion Example Results
after call k is 1 and result is 1
after call k is 2 and result is 3
after call k is 3 and result is 6
after call k is 4 and result is 10
after call k is 5 and result is 15
after call k is 6 and result is 21
但是如果我更改代码以返回 k:
def fib(k):
result = 0
if(k > 0):
result = k + fib(k - 1)
print(f'after call k is {k} and result is {result}')
else:
print()
#return result
return k
print("Recursion Example Results")
fib(6)
我明白了:
Recursion Example Results
after call k is 1 and result is 1
after call k is 2 and result is 3
after call k is 3 and result is 5
after call k is 4 and result is 7
after call k is 5 and result is 9
after call k is 6 and result is 11
为什么会有差异以及如何计算?为什么它不返回 k = 1,2,3,4,5,6?
在
fib(k + 1)
中,使用了fib(k)
的返回值。
因此,
fib(k)
返回k
还是result
很重要。