파이썬 계승 함수


135

파이썬에서 정수의 계승을 계산하는 방법은 무엇입니까?

답변:


191

가장 쉬운 방법은 사용하는 것입니다 math.factorial(Python 2.6 이상에서 사용 가능).

import math
math.factorial(1000)

직접 작성하고 싶은 경우 반복적 인 접근 방식을 사용할 수 있습니다.

def factorial(n):
    fact = 1
    for num in range(2, n + 1):
        fact *= num
    return fact

또는 재귀 접근법 :

def factorial(n):
    if n < 2:
        return 1
    else:
        return n * factorial(n-1)

있습니다 계승 기능이 당신이 또한 확인해야합니다, 그래서 오직 양의 정수에 대해 정의 n >= 0하고 그 isinstance(n, int). 그렇지 않은 경우 a ValueError또는 a를 TypeError각각 올리십시오 . math.factorial당신을 위해 이것을 돌볼 것입니다.


2
함수 factorial내에서 어떻게 사용할 수 있는지 이해하지 못합니다 factorial. 현재 정의하고있는 함수 내에서 같은 함수를 어떻게 사용할 수 있습니까? 저는 Python을 처음 사용하므로 이해하려고합니다.
J82

8
@ J82 : 여기에 사용 된 개념을 재귀 ( en.wikipedia.org/wiki/Recursion_(computer_science) )라고합니다. 함수 자체를 호출하는 것이 완벽하고 유용합니다.
schnaader

파이썬의 재귀 한계늘리지 않는 한 재귀 함수는 RecursionError998 (try factorial(999)) 보다 큰 숫자에 대해 를 증가시킵니다.
Boris

114

Python 2.6 이상에서는 다음을 시도하십시오.

import math
math.factorial(n)

Python 3.9부터이float 함수에 a 를 전달하면 a 가 발생합니다 DeprecationWarning. 그렇게 n하려면 int명시 적으로 다음 math.factorial(int(n))과 같이 변환해야 합니다. 소수점 이하 자릿수는 버립니다.n.is_integer()
Boris

25

이것은 오래된 스레드이기 때문에 실제로는 필요하지 않습니다. 그러나 여기에 while 루프를 사용하여 정수의 계승을 계산하는 또 다른 방법이 있습니다.

def factorial(n):
    num = 1
    while n >= 1:
        num = num * n
        n = n - 1
    return num

4
factorial (-1)은 1을 반환하고 ValueError 또는 무언가를 발생시켜야합니다.
f.rodrigues 2016 년

이 함수는 소수점 뒤에 숫자가있는 부동 소수점을 전달하면 잘못된 결과를 생성합니다.
Boris

이 함수를 사용하여 처음 네 정수의 계승을 인쇄하고 싶습니다. num = num * nwith와 함께 위치를 바꾸고 n = n - 1이것을 for i in range(1, 5): print('Factorial of', i, 'is', factorial(i))각 팩토리얼에 대해 실행할 때 , 출력은 0입니다. 나는 왜 num = num * n먼저 올 필요가 있는지에 대한 근거를 알고 싶습니다 . 감사!!

18

기존 솔루션

가장 짧고 아마도 가장 빠른 해결책은 다음과 같습니다.

from math import factorial
print factorial(1000)

자신의 건물

자신 만의 솔루션을 구축 할 수도 있습니다. 일반적으로 두 가지 접근 방식이 있습니다. 나에게 가장 적합한 것은 :

from itertools import imap
def factorial(x):
    return reduce(long.__mul__, imap(long, xrange(1, x + 1)))

print factorial(1000)

(결과가 될 때 더 큰 숫자에도 작동합니다 long)

이를 달성하는 두 번째 방법은 다음과 같습니다.

def factorial(x):
    result = 1
    for i in xrange(2, x + 1):
        result *= i
    return result

print factorial(1000)


5

Python2.5 또는 이전 버전을 사용하는 경우

from operator import mul
def factorial(n):
    return reduce(mul, range(1,n+1))

최신 Python의 경우 수학 모듈에 계승이 있으며 여기에 다른 답변이 나와 있습니다.


이것은 Python 2 전용 답변 reduce으로 Python 3에서 제거되었습니다.
Boris

@Boris는 Python3에 당신은 추가해야합니다from functools import reduce
존 라 Rooy을

이유 때문에 제거되었습니다, 당신은 그것을 사용해서는 안됩니다 artima.com/weblogs/viewpost.jsp?thread=98196
Boris

5
def fact(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f

4

for-loop를 사용하여 다음 부터 거슬러 올라갑니다 n.

def factorial(n):
    base = 1
    for i in range(n, 0, -1):
        base = base * i
    print(base)

3

성능상의 이유로 재귀를 사용하지 마십시오. 비참 할 것입니다.

def fact(n, total=1):
    while True:
        if n == 1:
            return total
        n, total = n - 1, total * n

실행 결과 확인

cProfile.run('fact(126000)')

4 function calls in 5.164 seconds

스택을 사용하는 것은 재귀 호출과 같이 편리하지만 비용이 많이 듭니다. 자세한 정보를 저장하면 많은 메모리를 차지할 수 있습니다.

스택이 높으면 컴퓨터가 함수 호출에 대한 많은 정보를 저장한다는 의미입니다.

이 방법은 반복과 같은 일정한 메모리 만 사용합니다.

또는 for 루프 사용

def fact(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

실행 결과 확인

cProfile.run('fact(126000)')

4 function calls in 4.708 seconds

또는 내장 함수 수학 사용

def fact(n):
    return math.factorial(n)

실행 결과 확인

cProfile.run('fact(126000)')

5 function calls in 0.272 seconds

1
나는이 while 루프가 조금 더 깨끗해 보인다고 생각합니다. <!-language : python-> def fact (n) : ret = 1 while n> 1 : n, ret = n-1, ret * n return ret
edilio

1
def factorial(n):
    result = 1
    i = n * (n -1)
    while n >= 1:
        result = result * n
        n = n - 1
    return result

print (factorial(10)) #prints 3628800

1

여기 내 시도가 있습니다

>>> import math
>>> def factorial_verbose(number):
...     for i in range(number):
...             yield f'{i + 1} x '
...
>>> res = ''.join([x for x in factorial_verbose(5)])
>>> res = ' '.join([res[:len(res)-3], '=', str(math.factorial(5))])
>>> res
'1 x 2 x 3 x 4 x 5 = 120'

@Nir Levy, 얼마나 재미있는 작은 일
Pedro Rodrigues

1

한 줄, 빠르고 많은 숫자도 작동합니다.

#use python3.6.x for f-string
fact = lambda x: globals()["x"] if exec(f'x=1\nfor i in range(1, {x+1}):\n\tx*=i', globals()) is None else None

0

나는 이것이 대답되었다는 것을 알고 있지만 여기에는 역 범위 목록 이해력을 가진 또 다른 방법이있어 범위를 읽기 쉽고 컴팩트하게 만듭니다.

    #   1. Ensure input number is an integer by attempting to cast value to int
    #       1a. To accomplish, we attempt to cast the input value to int() type and catch the TypeError/ValueError 
    #           if the conversion cannot happen because the value type is incorrect
    #   2. Create a list of all numbers from n to 1 to then be multiplied against each other 
    #       using list comprehension and range loop in reverse order from highest number to smallest.
    #   3. Use reduce to walk the list of integers and multiply each against the next.
    #       3a. Here, reduce will call the registered lambda function for each element in the list.
    #           Reduce will execute lambda for the first 2 elements in the list, then the product is
    #           multiplied by the next element in the list, and so-on, until the list ends.

    try :
        num = int( num )
        return reduce( lambda x, y: x * y, [n for n in range(num, 0, -1)] )

    except ( TypeError, ValueError ) :
        raise InvalidInputException ( "Input must be an integer, greater than 0!" )

이 요지 내에서 코드의 전체 버전을 볼 수 있습니다 : https://gist.github.com/sadmicrowave/d4fbefc124eb69027d7a3131526e8c06


1
사용할 필요는 [n for n in range(num, 0, -1)], range이미 반복 가능한 없습니다.
Mark Mishyn

0

이를 수행하는 다른 방법은 np.prod다음과 같이 사용 하는 것입니다.

def factorial(n):
    if n == 0:
        return 1
    else:
         return np.prod(np.arange(1,n+1))

0

계승n!으로 표시된 양의 정수 n의 은 n보다 작거나 같은 모든 양의 정수의 곱입니다.

공식 :n! = n * (n-1) * (n-2) * (n-3) * (n-4) * ....... * 1

내장 funtion / library 등을 사용하여 파이썬에서 계승을 찾는 방법은 여러 가지가 있습니다. 여기서는 계승의 기본 정의를 참조하여 사용자 정의 함수를 작성했습니다.

def factorial(n):
    fact = 1
    for i in range(1,n+1):
        fact = fact * i
    return(fact)

print(factorial(4))

recursive아래 그림과 같은 기술을 사용하여 계승 함수를 구현할 수도 있습니다. 그러나이 방법은 작은 정수 값에만 효율적입니다. 재귀에서 함수는 반복적으로 호출되며 스택을 유지하기 위해 메모리 공간이 필요합니다. 스택을 유지하기 위해서는 큰 정수 값에 대한 효율적이거나 최적화 된 접근 방식이 아닙니다.

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

print(factorial(4))


0

아래 코드에서 계승을 계산하려는 숫자를 입력 한 다음 계승 할 계산할 숫자에 1,2, ...., (계승 한 숫자)를 곱합니다. -1을 계산하고 싶습니다)

    f = int(input("Enter a number whose factorial you want to calculate = "))#Number 
                                           #whose factorial I want to calculate                              
for i in range(1,f): #assume I have taken f as 5
    f=f*i # In 1st iteration f=5*1 => 5 , in second iteration f = 5*2 => 10, 3rd 
          #iteration f = 10*3 =>30, 4th iteration f = 30*4 =>120  
print(f) #It will print the updated value of "f" i.e 120
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.