在递归 Python 函数中,为什么返回什么参数很重要?

问题描述 投票:0回答:1

我以为我理解递归函数,但意识到我实际上并不理解引擎盖下发生的事情

运行此 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?

python recursion return
1个回答
1
投票

fib(k + 1)
中,使用了
fib(k)
的返回值。

因此,

fib(k)
返回
k
还是
result
很重要。

© www.soinside.com 2019 - 2024. All rights reserved.