在Python中递归生成n阶乘的列表

编程入门 行业动态 更新时间:2024-10-27 08:28:46
本文介绍了在Python中递归生成n阶乘的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我无法在Python中实现此功能.我想编写一个具有(唯一)输入n的函数,该函数以递归方式生成阶乘值1的列表! ... n!

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!

到目前为止,我已经考虑过将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).

在这种情况下,我认为将列表作为函数的返回值传递是最简单的.它将在基本情况下创建,在此情况下,您将返回平凡的列表[1].每个外部调用都会将一个值附加到列表中(并使用以前在其上的最后一个值进行计算).

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

更多推荐

在Python中递归生成n阶乘的列表

本文发布于:2023-11-29 19:40:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   阶乘   列表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!