方法1: 使用递归
def myfact(n):
assert n >= 0, "Factorial not definied for negative values."
if n < 2:
return 1
else:
return n * myfact(n-1)
In [76]: myfact(6)
Out[76]: 720
def factorial(n): return reduce(lambda x,y:x*y,[1]+range(1,n+1))
In [78]: factorial(6) Out[78]: 720
方法3: 普通函数方式
def factorial(x):
result = 1
for i in xrange(2, x + 1):
result *= i
return result
In [82]: factorial(6)
Out[82]: 720
方法4: 使用imap
from itertools import imap def factorial(x): return reduce(long.__mul__, imap(long, xrange(1, x + 1)))
In [80]: factorial(6) Out[80]: 720L