Python因子递归函数

时间:2016-12-22 09:57:02

标签: python

有人可以一步一步地向我解释这个阶乘函数如何打印出这样的输出吗?我不明白为什么它打印所有阶乘然后跟中间语句,因为第一个n = 5不匹配n == 1所以它将转到else语句并打印出中间。

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

2 个答案:

答案 0 :(得分:3)

您正在使用递归函数来计算因子值。所以,当你达到其他声明时,

else:
    res = n * factorial(n-1)

控件转到调用函数" factorial(n-1)"再次而不是执行下一个语句。所以,当它再次召唤声明时,

print("factorial has been called with n = " + str(n))

将被打印。

因为," Stack"数据结构用于此递归函数。因此,每当控件进入函数调用语句时,程序的先前状态将被推入堆栈,并在" LIFO"中逐个弹出。方式。这就是输出原因的原因。

请参阅以下2个链接。你会更好地理解它。

https://www.youtube.com/watch?v=k0bb7UYy0pY

http://www.programmerinterview.com/index.php/recursion/explanation-of-recursion/

答案 1 :(得分:0)

确实,第一次打电话时n = 5。因此,您打印“factorial已被调用...”,然后不要输入“if n == 1”并转到“else”,它首先调用具有局部n = 4的阶乘,然后打印“中间结果。 ..“。每个factorial调用都会打印出那两个,除了最后一个factorial(1)调用,它不执行else语句,因此不打印“中间”事物。