vijay bhargav karnati
vijay bhargav karnati

Reputation: 29

How can we can we calculate the factorial of a number using python lambda function without recursion

I wanted to calculate the the factorial of a number using python lambda function without recursion.

I did without lamda function

def factorial_number(num):
fact = 1
while(num>=1):
    fact = num* fact;
    num = num-1
return  fact


factorial_number(5)

I have tried the below code without recursion(using lambda).

factorial_number  = lambda num : 1 while(num>=1) fact = fact*num num = num-1 return fact

The above code doesn't work.

Error:

File "<ipython-input-1-62f7b66fbfd2>", line 1
factorial_number  = lambda num : 1 while(num>=1) fact = fact*num num = num-1 return fact
                                   ^

SyntaxError: invalid syntax

But i want to implement using lamda function, without in-built functions and without recursive method. so that i can learn more how to use lamba funcitons effectively.

please help me with the code.

Upvotes: 0

Views: 402

Answers (3)

ProfessionalProdigy
ProfessionalProdigy

Reputation: 31

You can simply use math.factorial.

import math
fctrl = lambda: math.factorial(x)

or

from math import factorial
fctrl = lambda: factorial(x)

Upvotes: 0

user15801675
user15801675

Reputation:

You can use functools.reduce()

from functools import reduce
num = int(input('Enter number: '))
fact = lambda num: reduce(lambda x, y: x * y, range(1, num+1))

print(f'{num}! = {fact(num)}')

Upvotes: 1

Corralien
Corralien

Reputation: 120391

def factorial(n):
    t = 1
    for i in range(n, 1, -1):
        t *= i
    return t

>>> factorial(4)
24

Upvotes: 1

Related Questions