2011-09-09 6 views
0

1つの引数(数値)をとり、その数の階乗を返す関数を作成しようとしています。例えば、fのPythonのシーケンスの最初のn項の積

(5)* 5 * 4 * 3 1 * 2

私はこれまで

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つかかりますか?

+1

:その後、あなたのfactorial(n)はアイデンティティが、他の言葉でdef identity(n): return n

あるdef factorial(n): return product(n, identity)として定義されるだろうあなたの例では 'mul'とは何ですか? 'mul'が" multiply "を意味するなら、それはどのように一つの引数で動作するのですか? 'total * term(k、1)'ではなく 'term(total、k)'を意味するのではないですか?あなたは何をしようとしているのですか?これがどのように機能するのか、より詳細な説明を書くことができますか? –

答えて

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 fac(n): 
    return n * fac(n-1) if n > 1 else 1 
+0

これは階乗を呼び出すことなくこれを行うことが可能ですか? –

+0

私は別の機能のために後でproduct()を使う必要があるので、 –

+0

更新を参照してください。あなたの質問に答えますか? –

1

、nの階乗を計算するには、再帰関数の標準例です。 ?

import operator 

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

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

これは標準的な例かもしれませんが、単純な反復ループが同じくらい良く分かりやすく分かりやすい場合には、再帰を使用することは決してありませんでした。 – PaulMcG

1

何について:

def factorial(n): 
    if n == 0: 
     return 1 
    else: 
     return n * factorial(n-1) 
0

何を意味することはproduct(n, term)で、term(n)は、その時点での値にインデックスシリーズのnから関数であるべきということであれば、 「という用語は、1つのだけ引数を取る?」

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) 
関連する問題