반응형
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
반응형
'programing' 카테고리의 다른 글
Java에서 숫자를 단어로 변환하는 방법 (0) | 2023.02.06 |
---|---|
jQuery를 사용하여 하이퍼링크의 href 속성을 변경하는 방법 (0) | 2023.02.06 |
대소문자를 구분하지 않는 PHP in_array 함수 (0) | 2023.02.06 |
MySQL - 쿼리 속도를 테스트하기 위해 캐시를 사용하지 않음 (0) | 2023.02.06 |
도커가 다른 사용자로 localhost에서 mariadb에 연결할 수 없습니다. (0) | 2023.01.31 |