2011-09-09 7 views
0

하나의 인수 (숫자)를 취하여 그 수의 계승을 반환하는 함수를 만들려고합니다. 반환 예 F (5) 용파이썬에서 시퀀스의 첫 번째 n 항의 곱입니다.

1 * 2 * 3 * 4이란 지금까지이 것은, 그것이 용어되도록하는 것이 가능하다 그러나

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) 

5

이다 * 만 1 개의 인수가 필요합니까?

+1

당신의 모범에서'mul'은 무엇입니까? 'mul'이 "곱셈"을 의미한다면, 어떻게 하나의 인수로 작동 할 수 있습니까? '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

표준적인 예가 될 수 있지만 간단한 iterating 루프가 좋고 이해하기 쉬운 경우 재귀를 사용하여 필자는 결코 좋아하지 않았습니다. – PaulMcG

1

어떻 :

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

무엇을 의미하는 것은 product(n, term)에, term(n) 그 시점에서의 값에 일련의 인덱스 n에서 기능해야한다는 경우는 정체성 즉 def identity(n): return n

입니다 다음 factorial(n)def factorial(n): return product(n, identity)으로 정의 될 것입니다 : "용어 만 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) 
관련 문제