Function for Factorial in Python


Question

How do I go about computing a factorial of an integer in Python?

1
114
2/27/2011 10:22:46 PM

Easiest way: math.factorial(x) (available in 2.6 and above).

If you want/have to write it yourself, use something like

def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1))

or something more readable:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

As always, Google is your friend ;)

166
8/27/2015 2:15:48 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon