0

1 つの引数 (数値) を取り、その数値の階乗を返す関数を作成しようとしています。

たとえば、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

どうですか?

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 に答える
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

n の階乗の計算は、再帰関数の標準的な例です。

def fac(n):
    return n * fac(n-1) if n > 1 else 1
于 2011-09-09T11:44:03.210 に答える
0

あなたが意味するのは、 in は、一連のインデックスからその時点の値までの関数product(n, term)でなければならないということです。次に、アイデンティティがどこにあるかとして定義されますterm(n)nfactorial(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 に答える