[νμ΄μ¬/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
'πμκ³ λ¦¬μ¦ > π κ°λ μ 리' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[νμ΄μ¬/python] DFSμ BFS (0) | 2021.04.05 |
---|---|
[μκ³ λ¦¬μ¦] λΈλ£¨νΈν¬μ€ μκ³ λ¦¬μ¦ (Brute Force) (0) | 2021.04.02 |
[νμ΄μ¬/python] λμ κ³νλ² (Dynamic Programming) (0) | 2021.03.25 |
[νμ΄μ¬/python] ν (Queue) (0) | 2021.03.19 |
[νμ΄μ¬/python] μ λ ¬ - sort(), sorted() (0) | 2021.03.17 |