CS/Python

[Python] itertools 라이브러리

hyunji1109 2023. 7. 1. 21:47

 

from itertools import *

 

 

1. 순열

 

▪ permutations

 

구성 요소가 같더라도 순서가 다르면 나열

중복이 없는 모든 경우의 수 나열

 

from itertools import permutations

data = [ 1, 2, 3 ]

list(permutations(data, 2)
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

list(permutations(data, 2)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

 

 

2. 중복 순열

 

순열에서 같은 요소를 상관없이 중복 포함하여 모두 나열

 

from itertools import *

data = [ 1, 2, 3 ]

list(product(data, repeat = 2))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

 

 

3. 조합

 

▪ combinations

 

구성 요소가 같으면 순서가 다르더라도 출력하지 않음

중복이 없는 모든 경우의 수 나열

 

from itertools import combinations

data = [ 1, 2, 3 ]

list(combinations(data, 2))
[(1, 2), (1, 3), (2, 3)]

list(combinations(data, 3))
[(1, 2, 3)]

 

 

 

4. 중복 조합

 

조합에서 같은 요소를 상관없이 중복 포함하여 모두 나열

 

from itertools import *

data = [ 1, 2, 3 ]

list(combinations_with_replacement(data, 2)
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]