https://school.programmers.co.kr/learn/courses/30/lessons/120840

 

๋ฌธ์ œ

 

๋ฌธ์ œ ์„ค๋ช…

๋จธ์“ฑ์ด๋Š” ๊ตฌ์Šฌ์„ ์นœ๊ตฌ๋“ค์—๊ฒŒ ๋‚˜๋ˆ„์–ด์ฃผ๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ์Šฌ์€ ๋ชจ๋‘ ๋‹ค๋ฅด๊ฒŒ ์ƒ๊ฒผ์Šต๋‹ˆ๋‹ค. ๋จธ์“ฑ์ด๊ฐ€ ๊ฐ–๊ณ  ์žˆ๋Š” ๊ตฌ์Šฌ์˜ ๊ฐœ์ˆ˜ balls์™€ ์นœ๊ตฌ๋“ค์—๊ฒŒ ๋‚˜๋ˆ„์–ด ์ค„ ๊ตฌ์Šฌ ๊ฐœ์ˆ˜ share์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, balls๊ฐœ์˜ ๊ตฌ์Šฌ ์ค‘ share๊ฐœ์˜ ๊ตฌ์Šฌ์„ ๊ณ ๋ฅด๋Š” ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ return ํ•˜๋Š” solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

 

์ œํ•œ ์‚ฌํ•ญ

  • 1 ≤ balls ≤ 30
  • 1 ≤ share ≤ 30
  • ๊ตฌ์Šฌ์„ ๊ณ ๋ฅด๋Š” ์ˆœ์„œ๋Š” ๊ณ ๋ คํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
  • share ≤ balls

 

์ž…์ถœ๋ ฅ ์˜ˆ

balls share result
3 2 3
5 3 10

 

 

์†Œ์Šค ์ฝ”๋“œ
# 1 (๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ)
def solution(balls, share):
    answer = 1
    
    ball_list = list(range(balls,1,-1))
    share_list = list(range(1,share+1))
    
    for idx in range(1,share+1):
        answer *= ball_list[idx-1]
        answer = int(answer/share_list[idx-1])
    
    
    return answer

 

ํ’€์ด # 1

  • ๊ณต์˜ ๊ฐฏ์ˆ˜์—์„œ 1์”ฉ ๋นผ์„œ ball_list์— ๋‹ด๊ณ , ๊ณต์œ ํ•  ๊ณต์˜ ๊ฐฏ์ˆ˜๋ฅผ 1๋ถ€ํ„ฐ 1์”ฉ ๋”ํ•ด share_list์— ๋‹ด๊ธฐ
  • share ์ˆซ์ž ๋ฒ”์œ„์—์„œ ball_list์˜ ์›์†Œ๋Š” ๊ณฑํ•˜๊ณ  share_list์˜ ์›์†Œ๋Š” ๋‚˜๋ˆ„๊ธฐ

 

# 2
def solution(balls, share):
    answer = 1
    cnt = 0

    while cnt < share:
        answer *= (balls-cnt)
        answer = int(answer/(cnt+1))
        cnt += 1    
    
    return answer

 

ํ’€์ด #2

  • cnt๊ฐ€ share์˜ ์ˆซ์ž๋ณด๋‹ค ์ž‘์„๋™์•ˆ ๊ณฑํ•˜๊ธฐ์™€ ๋‚˜๋ˆ„๊ธฐ๋ฅผ ์‹คํ–‰
    • balls-cnt๋ฅผ ๊ณฑํ•˜๊ธฐ
    • ์œ„์˜ ์ˆซ์ž์—์„œ cnt+1์„ ๋‚˜๋ˆ„๊ธฐ 

 

# 3
import math

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

 

ํ’€์ด #3

  • math ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์—์„œ combination ํ•จ์ˆ˜ ์‚ฌ์šฉ

 

 

์ฒ˜์Œ์— ์ˆซ์ž๋ฅผ ๊ณฑํ•˜๊ณ  ๋‚˜๋ˆ„๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ํ•˜๋‹ค๊ฐ€ ์ž˜ ์•ˆ๋˜๊ธธ๋ž˜ ๋ฆฌ์ŠคํŠธ๋กœ ํ’€์–ด๋ดค๋Š”๋ฐ ์—ญ์‹œ๋‚˜ ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋‚ฌ๋‹ค. ๊ทธ๋ž˜์„œ ์ˆซ์ž๋ฅผ ์กฐ์ž‘ํ•ด์„œ while๋ฌธ์— ๋„ฃ์—ˆ๋”๋‹ˆ ๊ฒฐ๊ณผ๋Š” ๋‚˜์™”์ง€๋งŒ ๋ญ”๊ฐ€ ๋” ๋น ๋ฅด๊ฒŒ ๋‚˜์™”์œผ๋ฉด ์ข‹๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค. ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ํ’€์ด๋ฅผ ๋ณด๋‹ค๋ณด๋‹ˆ math ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์— combination ํ•จ์ˆ˜๊ฐ€ ์žˆ์—ˆ๋‹ค...๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ํ•จ์ˆ˜ ์“ฐ๋Š”๊ฑฐ ์ตœ๊ณ ...!!

+ Recent posts