[백준] 11050: 이항 계수 1 - 파이썬[python]

다인·2024년 10월 11일

백준

목록 보기
78/112
post-thumbnail

1. 반복문

  • 위의 팩토리얼을 함수로 구현하지 않고 반복문으로 직접 구하는 방식이다.
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
if K > N/2:
    K = N-K
result = 1

for i in range(1, K+1):
    result *= N
    result /= i
    N -= 1  

print(int(result))

2. 팩토리얼 함수 구현

import sys
input = sys.stdin.readline

N, K = map(int, input().split())

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

print(factorial(N) // (factorial(K)*factorial(N-K)))

3. combinations 모듈 이용

  • combinations(객체, k) 형식으로 쓰면 객체 안에서 순서를 신경쓰지 않고 k개씩 묶어 튜플 형태로 반환해 준다.
  • 순서를 신경쓰지 않기 때문에 중복되는 것을 걸러준다. 즉, ['A', 'B']와 ['B', 'A']를 같은 것으로 본다는 것이다.
  • 또한 객체는 반복 가능한 객체로, 리스트, 문자열, 튜플 등이 가능하다.
import sys
from itertools import combinations
input = sys.stdin.readline

N, K = map(int, input().split())

n = [i+1 for i in range(N)]
print(len(list(combinations(n, K))))
  • combinations는 튜플 형태로 반환한다고 했으므로 우리가 원하는 combination의 개수를 구하기 위해 list로 변경한 후 길이를 구한다.

0개의 댓글