python - Python 中的阶乘函数

标签 python

我是 Python 的新手,正在学习语法和各种功能。我想知道是否

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

是计算数字阶乘的正确函数吗?

亲切的问候

最佳答案

类似于 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)

关于python - Python 中的阶乘函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19491295/

相关文章:

python - 如何在 Python 中解析 SRV 记录?

python - 从终端杀死linux中的python解释器

python - 使用 matplotlib 时,带有 Anaconda 5.1.0 或更高版本的 Jupyter-Notebook 中的内存泄漏

python - 如何在 python 3 中定义 configparser

python - 无法在 Ubuntu 12.04 上安装 matplotlib

python - 退回多件贵重元素,然后分别调用这些贵重元素

python - 使用旧 python 版本的 mod_wsgi 运行时

python - sin(x)/x 的数值积分

python - 迭代子目录中的文本文件

python - findContours是否有理由给我一个错误,尽管它不应该这样吗?