0

Write a lambda function called factorials_1_to_n that computes the factorials of the numbers from 1 to n. Hint: Use the function factorial you already created.

The only thing I can think of doing is writing a for loop within the lambda function like.... for i in range(1,len(n)+1): factorial(i)…. but for loops are not allowed within a lambda function.

def factorial(n):
product=n
while n!=1:
    product=product*(n-1)
    n=n-1
return(product)
y=factorial(4)
print(y)


factorials_1_to_n = lambda n: ????????
y=factorials_1_to_n(4)
print(y)

1 Answers1

0

I assume that a list is an acceptable result type

factorials_1_to_n = lambda n: [factorial(i+1) for i in range(n)]

The i+1 is used to calculate it from 1 to n, instead of from 0 to n-1.

See list comprehension in python

pdpino
  • 444
  • 4
  • 13