Calculating Factorials with Lambda Functions

Write a Python lambda function that calculates the factorial of a number. Return the factorial.

Example 1:

Input: 5

Output: 120

Example 2:

Input: 6

Output: 720

Use a recursive approach within the lambda function to calculate the factorial.

# Define the lambda function
factorial = lambda n: 1 if n == 0 else n * factorial(n-1)

# Test the function
print(factorial(5)) # Output: 120
print(factorial(6)) # Output: 720

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!