본문 바로가기
🪡 코딩 테스트

[프로그래머스] 구슬을 나누는 경우의 수(factorial,comb/Python)

by b5ingbo2ng 2024. 7. 24.

문제 설명

머쓱이는 구슬을 친구들에게 나누어주려고 합니다. 구슬은 모두 다르게 생겼습니다. 머쓱이가 갖고 있는 구슬의 개수 balls와 친구들에게 나누어 줄 구슬 개수 share이 매개변수로 주어질 때, balls개의 구슬 중 share개의 구슬을 고르는 가능한 모든 경우의 수를 return 하는 solution 함수를 완성해주세요.

 

  • 서로 다른 구슬 3개 중 2개를 고르는 경우의 수는 3입니다.

 

- 시간초과로 틀렸던 코드

from itertools import combinations
def solution(balls, share):
    temp = list(range(1, balls+1))
    results = list(combinations(temp, share))
    result = len(results)
    return result



- math 라이브러리 comb 메소드로 더 쉽고 빠르게 해결가능!

import math
def solution(balls, share):
    return math.comb(balls, share)

 

 

- 팩토리얼을 쓰는 코드

from math import factorial as fac

def solution(balls, share):
	answer = 0
    n = fac(balls)
    m = fac(share)
    bottom = fac(balls-share) * m
    return n / bottom