0

我正在尝试创建一个函数,它接受一个参数(一个数字)并返回该数字的阶乘。

例如 f(5) 将返回 1*2*3*4*5

到目前为止我所拥有的是

def product(n, term):
    """Return the product of the first n terms in a sequence.

    term -- a function that takes one argument
    """
    k, total = 1, 1
    while k <= n:
        k, total = k + 1, total * term(k, 1)
    return total


def factorial(n):
    """Return n factorial by calling product.

    >>> factorial(4)
    24
    """
    return product(n, mul)

但是,是否有可能使该术语仅需要 1 个参数?

4

4 回答 4

1

计算 n 的阶乘是递归函数的标准示例:

def fac(n):
    return n * fac(n-1) if n > 1 else 1
于 2011-09-09T11:44:03.210 回答
1
import math

def factorial(n):
    return math.factorial(n)

替代实现:

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

使用递归:

def factorial(n):
     if n == 0:
         return 1
     else:
         return n * factorial(n-1)
于 2011-09-09T11:42:04.003 回答
1

关于什么?

import operator

def product(nums):
    return reduce(operator.mul, nums, 1)

def factorial(num):
    return product(range(2, num+1))
于 2011-09-09T13:15:32.833 回答
0

如果您的意思是 in product(n, term)term(n)应该是从n串联索引到该点的值的函数;那么你factorial(n)将被定义为def factorial(n): return product(n, identity)身份在哪里def identity(n): return n

换句话说:

def product(n, term):
    """Return the product of the first n terms in a sequence.

    term -- a function that takes one argument
    """
    k, total = 1, 1
    while k <= n:
        k, total = k + 1, total * term(k)
    return total


def identity(n):
    return n

def factorial(n):
    """Return n factorial by calling product.

    >>> factorial(4)
    24
    """
    return product(n, identity)
于 2011-09-09T14:08:30.053 回答