因此,在递归解决方案中,您不使用for循环,而是使用函数式编程模型,即使用堆栈作为循环
def recur_factorial(n):
total = 1
if n > 1:
total = n * recur_factorial(n - 1)
print(total)
return total
recur_factorial(5)
1
2
6
24
120
希望这能给你一个更好的想法,如果你的需求改变了,你可以调整这个模型来实现你所需要的。
更新
刚刚在你的评论中意识到你说函数需要返回
list
从2到n的阶乘。下面是更新的代码,返回一个列表。
def recur_factorial(n, factorials=[]):
if n == 1:
factorials.append(1)
else:
total = n * recur_factorial(n - 1)[-1]
factorials.append(total)
return factorials
factorials = recur_factorial(10)
print(factorials)
输出
[2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]