gpt4 book ai didi

python - 递归:为什么函数返回数字的阶乘而不是返回 1?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:28:32 24 4
gpt4 key购买 nike

def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)


def rec():
print fact(5)

rec()

[新手提问]

Python 脚本。

这个问题想了很久,说一下我目前对递归的理解。

rec()函数中我又调用了一个函数fact(5),现在流程转到fact(n)函数。

函数调用自身直到基本情况。

其他部分:

5 * fact( 4 )

5 * 4 * fact( 3 )

5 * 4 * 3 * fact( 2 )

5 * 4 * 3 * 2 * fact( 1 )

现在n的值变为0,返回1

我的问题是,为什么 fact(n) 函数返回 120 而不是 1。

def check(x):
if x == 1:
return 10
else:
return 20

print check(1) // Prints 10
print check(3) // Prints 20

我希望你理解我的问题。

谢谢。

最佳答案

这是计算 fact(5) 时堆栈的样子:

fact(5) = 5 * fact(4)
fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1 * fact(0)
fact(0) = 1
# no more recursive calls, unwind the stack
fact(1) = 1 * 1 = 1
fact(2) = 2 * 1 = 2
fact(3) = 3 * 2 = 6
fact(4) = 4 * 6 = 24
fact(5) = 5 * 24 = 120

希望对您有所帮助。每个缩进都是 fact(N) 返回的内容。

关于python - 递归:为什么函数返回数字的阶乘而不是返回 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com