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
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)
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.
def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1))
reduce(lambda x,y:x*y, xrange(1, n+1), 1)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.
factorialfunction from themathmodule.