[파이썬/python] μˆœμ—΄κ³Ό μ‘°ν•© : itertools μ΄μš©ν•˜κΈ° (permutations, combinations)

2021. 4. 1. 23:11

itertoolsλ₯Ό μ΄μš©ν•˜μ—¬ μˆœμ—΄κ³Ό 쑰합을 κ΅¬ν˜„ν•˜λ©΄ λ”μš± λΉ λ₯΄κ²Œ μ²˜λ¦¬ν•  수 μžˆλ‹€.

 

1. μˆœμ—΄ : permutations(N, r)

  • Nμ—μ„œ 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•Šκ³ , r개λ₯Ό 뽑아 μˆœμ„œλŒ€λ‘œ λ‚˜μ—΄ν•œλ‹€.
  • 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ—, 뽑은 것 쀑 같은 값이 λ‚˜μ˜¬ 수 μ—†λ‹€.
  • λ½‘νžŒ μˆœμ„œλŒ€λ‘œ λ‚˜μ—΄ν•˜κΈ° λ•Œλ¬Έμ— μˆœμ„œκ°€ μ€‘μš”ν•˜λ‹€.
  • 같은 값듀이 λ½‘νžˆλ”λΌλ„ μˆœμ„œκ°€ λ‹€λ₯΄λ©΄ λ‹€λ₯Έ κ²½μš°μ΄λ‹€.
from itertools import permutations

# for 문을 μ΄μš©ν•˜μ§€μ•Šκ³  κ΅¬ν˜„ν•˜κΈ°
print(list(map(''.join, permutations(['A', 'B', 'C']))))

>>> ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']

# for 문을 μ΄μš©ν•˜μ—¬ κ΅¬ν˜„ν•˜κΈ°
for i in permutations([1,2,3,4], 2):
    print(i, end=" ")

>>> (1, 2) (1, 3) (1, 4) (2, 1) (2, 3) (2, 4) (3, 1) (3, 2) (3, 4) (4, 1) (4, 2) (4, 3)

 

2. 쀑볡 μˆœμ—΄ : product(N, repeat=r)

  • Nμ—μ„œ 쀑볡을 ν—ˆμš©ν•˜κ³ , r개λ₯Ό 뽑아 μˆœμ„œλŒ€λ‘œ λ‚˜μ—΄ν•œλ‹€.
  • 쀑볡을 ν—ˆμš©ν•˜κΈ° λ•Œλ¬Έμ—, 뽑은 κ°’ λͺ¨λ‘κ°€ κ°™μ„μˆ˜λ„ μžˆλ‹€.
  • λ½‘νžŒ μˆœμ„œλŒ€λ‘œ λ‚˜μ—΄ν•˜κΈ° λ•Œλ¬Έμ— μˆœμ„œκ°€ μ€‘μš”ν•˜λ‹€.
  • 같은 값듀이 λ½‘νžˆλ”λΌλ„ μˆœμ„œκ°€ λ‹€λ₯΄λ©΄ λ‹€λ₯Έ κ²½μš°μ΄λ‹€.
from itertools import product

for i in product([1,2,3], repeat=2):
    print(i, end=" ")

>>> (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3)


for i in product(range(3), range(3), range(3)):
    print(i, end=" ")

>>>(0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 1, 0) (0, 1, 1) (0, 1, 2) (0, 2, 0) (0, 2, 1) (0, 2, 2) 
   (1, 0, 0) (1, 0, 1) (1, 0, 2) (1, 1, 0) (1, 1, 1) (1, 1, 2) (1, 2, 0) (1, 2, 1) (1, 2, 2)
   (2, 0, 0) (2, 0, 1) (2, 0, 2) (2, 1, 0) (2, 1, 1) (2, 1, 2) (2, 2, 0) (2, 2, 1) (2, 2, 2)

 

3. μ‘°ν•© : combinations(N, r)

  • Nμ—μ„œ 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•Šκ³ , r개λ₯Ό λ½‘λŠ”λ‹€.
  • 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ—, 뽑은 것 쀑 같은 값이 λ‚˜μ˜¬ 수 μ—†λ‹€.
  • λ½‘κΈ°λ§Œ ν•˜λ―€λ‘œ 뽑은 μˆœμ„œλŠ” μ€‘μš”ν•˜μ§€ μ•Šλ‹€.
  • 같은 값듀이 λ½‘νžˆλ©΄ μˆœμ„œλŠ” μ€‘μš”ν•˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ— 같은 κ²½μš°λ‹€.
from itertools import combinations

# for 문을 μ΄μš©ν•˜μ§€μ•Šκ³  κ΅¬ν˜„ν•˜κΈ°
print(list(map(''.join, combinations(['A', 'B', 'C'],2))))
>>> ['AB', 'AC', 'BC']

# for 문을 μ΄μš©ν•˜κ³  κ΅¬ν˜„ν•˜κΈ°
for i in combinations([1,2,3,4], 2):
    print(i, end=" ")

>>> (1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4)

 

4. 쀑볡 μ‘°ν•© : combinations_with_replacement(N, r)

  • Nμ—μ„œ 쀑볡을 ν—ˆμš©ν•˜κ³ , r개λ₯Ό λ½‘λŠ”λ‹€.
  • 쀑볡을 ν—ˆμš©ν•˜κΈ° λ•Œλ¬Έμ—, 뽑은 것 쀑 λͺ¨λ‘κ°€ κ°™μ„μˆ˜λ„ μžˆλ‹€..
  • λ½‘κΈ°λ§Œ ν•˜λ―€λ‘œ 뽑은 μˆœμ„œλŠ” μ€‘μš”ν•˜μ§€ μ•Šλ‹€.
  • 같은 값듀이 λ½‘νžˆλ©΄ μˆœμ„œλŠ” μ€‘μš”ν•˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ— 같은 κ²½μš°λ‹€.
from itertools import combinations_with_replacement

for i in combinations_with_replacement([1,2,3,4], 2):
    print(i, end=" ")
    
>>> (1, 1) (1, 2) (1, 3) (1, 4) (2, 2) (2, 3) (2, 4) (3, 3) (3, 4) (4, 4)
728x90

BELATED ARTICLES

more