需要对递归进行一些澄清

时间:2018-01-28 05:11:14

标签: python recursion

最近我发现了一些关于递归的Python教程的代码,它是一个基本的阶乘递归:

def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
    return 1
else:
    res = n * factorial(n-1)
    print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
    return res  
print(factorial(5))

这是控制台输出:

factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for  2  * factorial( 1 ):  2
intermediate result for  3  * factorial( 2 ):  6
intermediate result for  4  * factorial( 3 ):  24
intermediate result for  5  * factorial( 4 ):  120
120

在做了一些研究后,我觉得我已经了解了为什么这是输出但是我想确定。根据我的理解:

它重复else语句4次,并将n值和res值放入调用堆栈。当res调用factorial(1)时,它会转到基本情况并停止递归,因此我们可以检索堆栈数据。它弹出n = 1并且不打印任何输出,但随后弹出2,3,4,5并检索它们在递归期间计算的res值。最后一旦res返回足够,我们在堆栈顶部留下5 * 24(n * res),Python知道要返回打印的值(factorial(5))。

这是所有正确的信息吗,我错过了什么吗?如果有任何不正确之处,请告诉我,或者指出一些可以澄清这一点的资源。谢谢!

1 个答案:

答案 0 :(得分:2)

是的,你是对的。

注意在

之前如何调用factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)

这就是为什么你首先在'"中间结果"之前获得"factorial has been called"打印消息的原因。打印。