코딩테스트/Python 개념

[Python] 조합, 순열 리스트 말고 값으로 출력 math.comb / math.perm

박소민 2023. 3. 29. 12:13
math.comb(n, k)

nCk와 같은 조합 값을 반환

조합은 n개의 수 중 k개를 꺼내는 수와 동일

import math
 
print("math.comb(5, 1) = " + str(math.comb(5, 1)))
print("math.comb(5, 2) = " + str(math.comb(5, 2)))
print("math.comb(10, 1) = " + str(math.comb(10, 1)))
print("math.comb(10, 4) = " + str(math.comb(10, 4)))
#결과
math.comb(5, 1) = 5
math.comb(5, 2) = 10
math.comb(10, 1) = 10
math.comb(10, 4) = 210

 

 

math.perm(n, k)

nPk와 같은 순열 값을 반환

n개의 수 중 k개를 꺼내서 나열하는 경우의 수

import math
 
print("math.perm(5, 1) = " + str(math.perm(5, 1)))
print("math.perm(5, 2) = " + str(math.perm(5, 2)))
print("math.perm(10, 1) = " + str(math.perm(10, 1)))
print("math.perm(10, 4) = " + str(math.perm(10, 4)))
math.perm(5, 1) = 5
math.perm(5, 2) = 20
math.perm(10, 1) = 10
math.perm(10, 4) = 5040

 


관련 문제 ) 백준 1010. 다리 놓기
 

1010번: 다리 놓기

입력의 첫 줄에는 테스트 케이스의 개수 T가 주어진다. 그 다음 줄부터 각각의 테스트케이스에 대해 강의 서쪽과 동쪽에 있는 사이트의 개수 정수 N, M (0 < N ≤ M < 30)이 주어진다.

www.acmicpc.net

  • 파이썬
import math
test=int(input())
for tc in range(test):
  n,m=map(int,input().split())
  print(math.comb(m,n))