AndroidDev
AndroidDev

Reputation: 16405

Factorial function in Python

I am new to Python, and am just learning the syntax and various functions. I would like to know if

x=reduce((lambda x,y: x*y) , [x for x in range(5) if x > 0])

is a correct function for calculating the factorial of a number ?

Kind Regards

Upvotes: 2

Views: 924

Answers (5)

mshsayem
mshsayem

Reputation: 18018

Short:

x = reduce(lambda x,y: x*y, range(1,5))

Shorter, Instead of a lambda:

from operator import mul
x = reduce(mul, range(1,5))

Or Shortest, from math module (thanks to hop):

from math import factorial
factorial(4) # range/xrange above does not include the upper value

Upvotes: 4

georg
georg

Reputation: 215029

Something along the lines of http://www.willamette.edu/~fruehr/haskell/evolution.html

# beginner

def fac(n):
    f = 1
    i = 1
    while i <= n:
        f *= i
        i += 1
    return f

# advanced beginner

def fac(n):
    return n * fac(n - 1) if n > 1 else 1

# intermediate

def fac(n):
    return reduce(lambda x, y: x * y, range(1, n + 1))

# advanced intermediate

import operator
def fac(n):
    return reduce(operator.mul, xrange(1, n + 1))

# professional

import math
print math.factorial(5)

# guru

import scipy.misc as sc
print sc.factorial(5, exact=True)

Upvotes: 6

Diego Herranz
Diego Herranz

Reputation: 2947

Another approach using recursion:

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

Anyway, it's better to use math.factorial.

Upvotes: 1

AlvaroAV
AlvaroAV

Reputation: 10563

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

Upvotes: 1

Sneftel
Sneftel

Reputation: 41522

Pretty much -- though if you want 5!, you should do range(6). Also, a small stylistic issue: you should surround your generator expression with parentheses instead of brackets, so that a temporary list doesn't need to be constructed. Finally, the if-clause isn't necessary -- just use the two-argument version of range.

Upvotes: 3

Related Questions