programing

python에 math nCr 함수가 있나요?

bestcode 2023. 2. 6. 23:33
반응형

python에 math nCr 함수가 있나요?

python의 수학 라이브러리에 내장된 기능이 nCr (n Choose r) 함수인지 확인하려고 합니다.

여기에 이미지 설명 입력

프로그래밍이 가능한 것은 알고 있습니다만, 사전에 빌트인 되어 있는지 확인해 보려고 생각하고 있습니다.

다음 프로그램은 다음을 계산합니다.nCr효율적인 방법으로(계수 계산 등)

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

Python 3.8에서 이항 계수는 표준 라이브러리에서 다음과 같이 사용할 수 있습니다.math.comb:

>>> from math import comb
>>> comb(10,3)
120

반복하시겠습니까?itertools.combinations.일반적인 사용법:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

공식을 계산해야 하는 경우에는 math.factorial을 사용할 수 있지만 큰 조합에서는 빠르지 않습니다.math.comb다음은 Python 3.8+에서 사용할 수 있는 최적화된 계산입니다.

import math

def nCr(n,r):
    f = math.factorial
    return f(n) // f(r) // f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

출력:

6

Python 3.8에서는math.comb사용할 수 있고 훨씬 더 빠릅니다.

>>> import math
>>> math.comb(4,2)
6

언급URL : https://stackoverflow.com/questions/4941753/is-there-a-math-ncr-function-in-python

반응형