簡體   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