간혹가다가 내가 가진 자료 구조에서 순열 혹은 조합에 의거해서 요소를 뽑아야할 때가 있다. 루프를 돌려서 하려면 번거롭기 때문에, 이럴 때에는 itertools에서 permutation, combination, combination with replacement, product를 사용하면 매우 편하게 출력할 수 있다.
공통적으로 순서쌍들을 튜플에 담긴 iterable한 객체로 반환하니, 리스트 같은데 담거나 for를 사용하여 루프를 돌려 사용하면 된다. next()를 사용해도 되지만 굳이...?
from itertools import permutations
newList = [i for i in range(3)]
for i in permutations(newList, 2):
print(i, end=' ') # (0, 1) (0, 2) (1, 0) (1, 2) (2, 0) (2, 1)
# permutaions(<순회할거>, <몇번?>) 형식으로 사용
print(list(permutations(newList, 3)))
#[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
permutations, 순열부터 말하자면 말 그대로 순서를 따지면서 뽑는 순서대로 나열하는 경우다.총 갯수는 nPr = n! / (n-r)! 이므로 위의 경우에서는 3P2 = 3!/1! = 6, 아래 경우 역시 3P3 = 3!/0! = 6 이다.
from itertools import combinations
newList = [i for i in range(3)]
# permutaions(<순회할거>, <몇번?>) 형식으로 사용
print(list(combinations(newList, 3))) #[(0, 1, 2)]
Combination, 조합은 중복을 허용하지 않고 순서에 상관 없이 뽑는 경우이다. 총 갯수는 nCr = nPr / r! = n!/(r!(n-r)!) 이므로 따라서 3개 중에서 3개를 뽑는 것은 단 하나의 경우밖에 나오지 않는 걸 확인 할 수 있다.
from itertools import combinations_with_replacement
newList = [i for i in range(3)]
print(list(combinations_with_replacement(newList, 3)))
#[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 1), (0, 1, 2), (0, 2, 2), (1, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 2)]
combination_with_replacement, 중복을 허용하면서 순서에 상관없이 뽑는 경우이다. 중복조합의 총 갯수는 nHr = n+r-1Cn-1 = (n+r-1)!/(r!(n-1)!) = 5!/3!2! = 10개 이다.
from itertools import product
newList = [i for i in range(3)]
#다른 것과는 달리 repeat= 을 기입하여 사용한다.
print(list(product(newList, repeat=2)))
#[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
데카르트 곱을 생성한다. 제한없는 for n중 루프랑 똑같다. 총 갯수는 n^(repeat)
'Python > Python' 카테고리의 다른 글
제너레이터, 이터레이터, 코루틴 (0) | 2023.04.19 |
---|---|
Python : match (0) | 2023.04.06 |
Python : 표현식(Comprehension) (1) | 2023.03.24 |
Python : 클로저(Closure), 데코레이터(Decorator) (0) | 2023.03.23 |
Python : 컨텍스트 관리자, with <객체> as <변수명> (0) | 2023.03.23 |