繁体   English   中英

Python中序列中前n个项的乘积

[英]Product of first n terms in a sequence in python

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

例如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个参数?

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)

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

def fac(n):
    return n * fac(n-1) if n > 1 else 1

关于什么?

import operator

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

def factorial(num):
    return product(range(2, num+1))

如果您的意思是在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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM