์ƒˆ์†Œ์‹

๐Ÿงฎ ์•Œ๊ณ ๋ฆฌ์ฆ˜

์ˆœ์—ด๊ณผ ์กฐํ•ฉ ( n! , nPr , nCr ) - (itertools) combinations, permutations + ์ค‘๋ณต์ˆœ์—ด, ์ค‘๋ณต์กฐํ•ฉ

  • -

*n! (Factorial, ํŒฉํ† ๋ฆฌ์–ผ)

1๋ถ€ํ„ฐ ์ž์—ฐ์ˆ˜ n๊นŒ์ง€์˜ ๋ชจ๋“  ์ˆ˜๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ๊ณฑํ•˜๋Š”๊ฒƒ. (์ฃผ์˜ 0! = 1)

 

math๋ชจ๋“ˆ

ํŒŒ์ด์ฌ์—์„œ ํŒฉํ† ๋ฆฌ์–ผ์„ ๊ตฌํ• ๋•Œ๋Š” math๋ชจ๋“ˆ์„ ์ด์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

import math

math.factorial(5)

 

 

 

 


 

 

*nPr (permutation, ์ˆœ์—ด)

์ด๋ฆ„๋Œ€๋กœ ๋ฝ‘์•„์„œ, ์ค„์„ ์„ธ์šฐ๋Š” ์ƒํ™ฉ์—์„œ ์ˆœ์—ด์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. (์ค„์„ ์„ธ์šด๋‹ค๋Š”๊ฒƒ์€ ์ˆœ์„œO ๋ผ๋Š” ๋œป)

์ฆ‰, ์ˆœ์„œ๊ฐ€ ์žˆ์„๋•Œ. ๊ทธ๋ฆฌ๊ณ  ์ค‘๋ณต์ด ์—†์„๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

n : ์ „์ฒด ๊ฐœ์ˆ˜  r : ๋ฝ‘์„ ๊ฐœ์ˆ˜ 

 

itertools ๋ชจ๋“ˆ - permutations ํ•จ์ˆ˜

ํŒŒ์ด์ฌ์—๋Š” ์ˆœ์—ด์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋Š” ๋‚ด์žฅํ•จ์ˆ˜๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. 

import itertools

alphabet = ["a","b","c"]
w = itertools.permutations(alphabet)
print(list(w))
์ถœ๋ ฅ : [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

 

 

 

 

 

 

* ์ค‘๋ณต์ˆœ์—ด Permutation with Repetition

์ˆœ์„œ๋Œ€๋กœ ๋ฝ‘์œผ๋ฉฐ, ์ค‘๋ณต์„ ํ—ˆ์šฉํ• ๋•Œ. (์ˆœ์—ด๊ณผ ๊ฐ™์ง€๋งŒ ์ค‘๋ณต์„ ํ—ˆ์šฉ)

itertools๋ชจ๋“ˆ - productํ•จ์ˆ˜
import itertools 

alphabet = ["a","b","c"]
w = itertools.product(alphabet, repeat=2)
print(list(w))
์ถœ๋ ฅ : [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]

repeat๋ฅผ ํ†ตํ•ด์„œ, ๋ช‡๊ฐœ๋ฅผ ๋ฝ‘์„์ง€ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

 

 

 

*nCr (combination, ์กฐํ•ฉ)

์ˆœ์„œ๊ฐ€ ์—†๋Š” ์ˆœ์—ด์ž…๋‹ˆ๋‹ค . ์ฆ‰, ๊ทธ๋ƒฅ ์ „์ฒด์—์„œ ํŠน์ •๊ฐœ์ˆ˜๋ฅผ ๋ฝ‘๊ธฐ๋งŒ ํ•ฉ๋‹ˆ๋‹ค.

 

n : ์ „์ฒด๊ฐœ์ˆ˜

r : ๋ฝ‘์„ ๊ฐœ์ˆ˜

 

 

itertools ๋ชจ๋“ˆ - combination ํ•จ์ˆ˜

๋งˆ์ฐฌ๊ฐ€์ง€๋กœ itertools ๋ชจ๋“ˆ์— combinationํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ฉ๋‹ˆ๋‹ค.

a,b,c ์„ธ๊ฐœ์ค‘ 2๊ฐœ๋ฅผ ๋ฝ‘๋Š”๊ฒฝ์šฐ๋Š” ๋‹ค์Œ ์ฝ”๋“œ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

from itertools import combinations

alphabet = ["a","b","c"]
a = list(combinations(alphabet,2))
print(a)
์ถœ๋ ฅ : [('a', 'b'), ('a', 'c'), ('b', 'c')]

 

 

 

*์ค‘๋ณต ์กฐํ•ฉ combination with repetition

 

itertools - combinations_with_replacement ํ•จ์ˆ˜
from itertools import combinations_with_replacement

alphabet = ["a","b","c"]
a = list(combinations_with_replacement(alphabet,2))
print(a)
์ถœ๋ ฅ : [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]

 

 

 

 

 


 

 

* map ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ, ๋ณด๊ธฐ ํŽธํ•˜๊ฒŒ ์ถœ๋ ฅํ•˜๊ธฐ

๋ฆฌ์ŠคํŠธ ์•ˆ์˜ ํŠœํ”Œํ˜•ํƒœ๋กœ ์ถœ๋ ฅ์ด ๋˜๋Š”๋ฐ, ์ข€ ๋” ํŽธ์˜์„ฑ์„ ์œ„ํ•ด mapํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋‹ค์Œ์ฒ˜๋Ÿผ ์ถœ๋ ฅ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

mapํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ถœ๋ ฅ
import itertools

alphabet = ["a","b","c"]
w = itertools.permutations(alphabet)
print(list(map("".join, w)))
์ถœ๋ ฅ : ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

 

 

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.