[Python] itertools 모든 경우의 수 (순열, 조합, 데카르트 곱) 구하는 방법

반복과 관련된 파이썬 라이브러리 itertools에서 product(), permutations(), combinations(), combinations_with_replacement() 같은 조합형 이터레이터를 활용하여 쉽게 순열, 조합 및 데카르트 곱등을 구하는 방법에 대해 다루어 보겠습니다.

순열 permutations

itertools 라이브러이에 있는 메서드이기 때문에 import 하고 사용해야 합니다.

다음 예시처럼 반복 가능한 객체(리스트, 문자열 등)를 permutations() 메서드에 인자로 넣어주면 순열을 반환합니다.

추가로 2.에서처럼 repeat 매개변수를 의미하는 숫자를 인자로 넣어주면 해당 개수만큼만 요소를 사용하는 순열을 반환합니다. 1.에서 볼 수 있듯이 repeat 매개변수를 따로 지정해주지 않으면 기본값으로 사용할 수 있는 요소의 최대 개수가 지정됩니다.

import itertools

li = ["A", "B", "C"]

print("1.")
for p in itertools.permutations(li):
    print(p)

print("2.")
for p in itertools.permutations(li, 2):
    print(p)

결과값:

permutations

조합 combinations

조합을 구하고 싶다면 combinations() 메서드를 사용해야 합니다. 마찬가지로 itertools 라이브러리에 있기 때문에 import한 후 사용할 수 있습니다.

함수 호출 방식에 있어 permutations()와 다른 점은 무조건 repeat 매개변수로 숫자를 반복 가능한 객체와 함께 전달해야합니다.

from itertools import combinations

l = [1, 2, 3, 4, 5]

for c in combinations(l, 3):
    print(c)

결과값:

combinations

요소가 중복될 수 있는 조합을 구한다면, combinations_with_replacement() 메서드를 사용하면 됩니다.

from itertools import combinations_with_replacement

l = [1, 2, 3, 4, 5]

for c in combinations_with_replacement(l, 2):
    print(c)

결과값:

combinations_with_replacement

데카르트 곱 product

product() 메서드를 활용하여 두 iterable 객체의 데카르트곱을 구할 수 있습니다.

1.에서처럼 두개의 객체 l1과 l2를 매개변수로 넣고 product를 호출하면 두 객체 집합의 데카르트 곱을 반환합니다.

2.에서처럼 추가로 repeat 매개변수를 지정할 수 있습니다. 기본값은 1입니다. 2.에서처럼 “repeat=2″로 지정한 경우 각 집합에서 repeat 개수만큼 요소를 사용해서 데카르트 곱을 구합니다.

( 예로, product( l1, l2, repeat=2)product(l1, l2, l1, l2)와 같습니다. )

3.에서처럼 하나의 iterable 객체만 넣은 경우, repeat 매개변수의 개수만큼 데카르트 곱을 구하는 것과 같습니다.

( 예로, product(l1, repeat=3)product(l1, l1, l1)와 같습니다. )

from itertools import product

l1 = ["A", "B"]
l2 = ["1", "2"]

print("1.")
for i in product(l1, l2):
    print(i)

print("2.")
for i in product(l1, l2, repeat=2):
    print(i)

print("3.")
for i in product(l1, repeat=3):
    print(i)

결과값:

product

답글 남기기