[Python] 순열, 조합, 중복 순열, 중복 조합
파이썬에서 itertools 라이브러리를 통해 조합과 순열을 쉽게 사용할 수 있다.
itertolls : 효율적인 루핑을 위한 이터레이터를 만드는 함수 = 효율적으로 iterator (값을 차례대로 꺼낼 수 있는 객체)를 생성해주는 모
조합 및 순열을 사용하기 위해 itertools 모듈에서 다음 함수를 사용할 수 있다.
1. 조합 (Combination)
중복x, 순서x
combinations(iterable, r) : iterable 에서 원소 개수가 r개인 조합 뽑기
from itertools import combinations
iter = [1,2,3,4]
for i in combinations(iter, 2):
print(i)
# 출력 결과
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
2. 중복 조합
중복o, 순서x
combinations_with_replacement(iterable, r) : iterable 에서 원소 개수가 r개인 중복 조합 뽑기
from itertools import combinations_with_replacement
iter = [1,2,3,4]
for i in combinations_with_replacement(iter, 2):
print(i)
# 출력 결과
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 2)
(2, 3)
(2, 4)
(3, 3)
(3, 4)
(4, 4)
3. 순열 (Permutation)
중복x, 순서o
permutations(iterable, r =None) : iterable 에서 원소 개수가 r개인 순열 뽑기
from itertools import permutations
iter = [1,2,3,4]
for i in permutations(iter, 2):
print(i)
# 출력 결과
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
이때 r을 지정하지 않거나 r = None으로 하면 최대 길이 순열이 리턴된다.
4. 중복 순열
product(*iterables, repeat = 1) : 여러 iterable 요소들의 순서쌍을 반환하는 iterator 생성
- repeat : 하나의 iterable에서 반복할 횟수
from itertools import product
iter = [1,2,3,4]
for i in product(iter, repeat=2):
print(i)
# 실행 결과
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
(4, 4)
5.
위에서는 입력받은 i가 (1,2,3)과 같이 괄호에 묶여 출력된다. 이때 각 값을 받고 싶다면 다음과 같이 코드를 작성하면 된다.
from itertools import permutations
arr = [1,2,3,4]
for i in permutations(arr, 3) :
a,b,c = i
print(a,b,c)
'''
result :
1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
'''