Python lambda function to calculate factorial of a number

前端 未结 11 1323
误落风尘
误落风尘 2020-12-30 12:00

I have just started learning python. I came across lambda functions. On one of the problems, the author asked to write a one liner lambda function for factorial of a number.

11条回答
  •  醉酒成梦
    2020-12-30 13:00

    Easy Method to find Factorial using Lambda Function

    fac = lambda x : x * fac(x-1) if x > 0 else 1
    
    print(fac(5))
    

    output: 120

    User Input to find Factorial

    def fac():
    
        fac_num = int(input("Enter Number to find Factorial "))
    
        factorial = lambda f : f * factorial(f-1) if f > 0 else 1
    
        print(factorial(fac_num))
    
    fac()
    

    Enter Number to find Factorial : 5

    120

提交回复
热议问题