Recursively generates a list of n factorials in Python

I am having trouble implementing this in Python. I want to write a function with (single) input n, which recursively generates a list of factor values ​​1! ... n!

So far I have been thinking about storing the recursively obtained n-factorial values ​​in a variable and then adding (pressing?) Them to the list. The question I have is how do I β€œsave” a list? I am not sure how to check if a list exists or not.

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 = []
+2
source share
3 answers

. , , , (, , , ).

, , . , [1]. ( , ).

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
+3

, . ?

def fact_wrapper(n):
    lst = [1]
    def fact(n):
        if n == 0 or n==1:
            return 1
        else:
            a = n * fact(n-1)
            lst.append(a)
            return a

    fact(n)
    return lst


print(fact_wrapper(5)) 

:

[1, 2, 6, 24, 120]

, :

def factorial(n):
    result = 1
    for i in range(1,n+1):
       result *= i
       yield result

print list(factorial(5))

:

[1, 2, 6, 24, 120]

next() . python, this.

+3

, , :

  • , , (n == 1) , .
  • - (n > 1) - ! , - .

. , , , , .

def gen_factorial(n):
    if n == 1:
        yield 1
    else:
        for u in gen_factorial(n - 1):
            yield u
        yield u * n

for u in gen_factorial(5):
    print(u)

print(list(gen_factorial(8)))

1
2
6
24
120
[1, 2, 6, 24, 120, 720, 5040, 40320]
+3

Source: https://habr.com/ru/post/1687013/


All Articles