[제로베이스] [기초 수학] 경우의 수, 확률

한결·2023년 12월 16일
0
post-thumbnail

1. 팩토리얼

팩토리얼
1부터 양의 정수 n까지의 정수를 모두 곱한 것
ex) 5! = 1x2x3x4x5


2.순열

순열
n개에서 r개를 택하여 나열하는 경우의 수

nPr = n(n-1)...(n-r+1) (단, 0<r≤n)
ex) 8P3 = 8x7x6 = 336


파이썬을 이용해서 다음 순열들의 값을 구하는 프로그램을 만들어보자.

n = int(input('n 입력: '))
r = int(input('r 입력: '))
nPr = 1

for i in range(1,r+1):
    nPr *= n-i+1
    print(f'n : {n-i+1}')

print(f'result = {nPr}')

원순열
시작과 끝의 구분이 없는 순열

(n-1)!


3.조합

조합
n개에서 r개를 택하는 경우의 수

nCr = {n(n-1)...(n-r+1)} / (r!) (단, 0<r≤n)
ex) 8C3 = (8x7x6)/(3x2x1) = 56


파이썬을 이용해서 다음 조합들의 값을 구하는 프로그램을 만들어보자.

n = int(input('n 입력: '))
r = int(input('r 입력: '))
nPr = 1
fact = 1 # 분모로 갈 팩토리얼

for i in range(1,r+1):
    nPr *= n-i+1
    fact *= i
    print(f'n : {n-i+1}')

print(f'result = {int(nPr/fact)}')

4. 확률

확률
모든 사건에서 특정 사건이 일어날 수 있는 수를 나타낸 것


박스에 '꽝'이 적힌 종이가 4장 있고, '선물'이 적힌 종이가 3장이 있을 때, 파이썬을 이용해서 '꽝' 2장과 '선물' 1장을 뽑는 확률(%)을 출력하자.

nope = int(input('꽝의 총 개수 : '))
yeap = int(input('당첨 총 개수 : '))

total = nope + yeap

nope_sel = int(input('뽑는 꽝의 개수 : '))
yeap_sel = int(input('뽑는 당첨 개수 : '))

total_sel = nope_sel + yeap_sel

def nCr(n,r) :
    nPr = 1
    fact = 1

    for i in range(1,r+1):
        nPr *= n-i+1
        fact *= i

    return(int(nPr/fact))

prob = (nCr(nope,nope_sel)*nCr(yeap,yeap_sel))/nCr(total,total_sel) *100

print('probability: %.2f%%'%prob)
profile
낭만젊음사랑

0개의 댓글