Python 实现n阶乘

来源:互联网 发布:淘宝秒杀怎么没有了 编辑:程序博客网 时间:2024/05/01 10:54

方法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


方法2: 使用匿名函数
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 imapdef factorial(x):    return reduce(long.__mul__, imap(long, xrange(1, x + 1)))
In [80]: factorial(6)Out[80]: 720L
0 0