在Python中递归生成n阶乘的列表 [英] Recursively generating a list of n factorial in Python

查看:521
本文介绍了在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阶乘的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆