当前位置:   article > 正文

python用递归法求n的阶乘,在Python中递归生成n阶乘的列表

python 递归函数生成阶乘列表

I am having trouble implementing this in Python. I want to write a function with (sole) input n, that recursively generates a list of factorial values 1! ... n!

So far I have thought of storing the recursively derived values of n-factorial in a variable, and then adding (pushing?) them into a list. The question I have is how do I 'save' the list? I am not sure how to check if a list exists or not as well...

def recFactorial(n):

if n == 1:

return 1

print(l)

else:

l = []

f = n * recFactorial(n-1)

if l:

l = l.push(f)

else:

l = []

解决方案

Recursive function calls can't see the local variables of the other calls to the same function. If you want several calls to be able to work with the same list, the list needs to either be a parameter or a return value of the function (or I suppose a global variable, but that would be really bad design).

In this case, I think it would be easiest to pass the list as the return value of the function. It would be created in the base case, where you'd return the trivial list [1]. Each outer call would append a value to the list (and use the last value that was on it previously to do their calculation).

def recFactorialList(n):

if n == 1:

return [1] # base case, still returns a list

lst = recFactorialList(n-1)

n_fac = lst[-1] * n # use the last value to calculate a new value

lst.append(n_fac) # add n factorial to the end of the list

return lst # return the updated list

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/212653
推荐阅读
相关标签
  

闽ICP备14008679号