Programing/Python

itertools

mjune.kim 2019. 6. 6. 12:21

안녕하세요.

itertools 는 확률에서 많이 사용되는 조합, 집합 등의 연산을 수행할 수 있도록 제공되는 모듈인데요.

고등학교 또는 대학교때 머리 싸매고 외웠던 순열/조합에 대한 연산을 단 한줄로 손쉽게 구할 수 있습니다.

수학적 모델링을 구현하고 계산할때 이 모듈을 많이 사용할 것 같은 느낌(?)이 드네요..ㅠ.ㅠ

학창시절 수학을 좋아하긴 했지만 시간이 지나서 다시 공부를 해야 하는 상황에는 조금 걱정이 앞서네요.

1) itertools import 하기

1
2
3
4
from itertools import combinations
from itertools import combinations_with_replacement
from itertools import permutations
from itertools import product

2) product

중복 순열로 중복을 허용하며 일렬로 세울수 있는 모든 경우에 대한 조합입니다.

1
2
3
4
5
from itertools import product
 
print (list(product('ABCD', repeat=2)))
---
[('A''A'), ('A''B'), ('A''C'), ('A''D'), ('B''A'), ('B''B'), ('B''C'), ('B''D'), ('C''A'), ('C''B'), ('C''C'), ('C''D'), ('D''A'), ('D''B'), ('D''C'), ('D''D')]
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none; color:white">cs

3) permutations

한국말로는 순열이라고 불리는데 정의에 따르면 정의역과 공역이 일대일 대응이 되는 집합이라고 합니다.

복잡해보이는데 쉽게 말하면 모든 엘리먼트가 각 자리에 한번씩은 들어갈 수 있다는 의미입니다.(순서 상관 있음)

1
2
3
4
5
from itertools import permutations
 
print list(permutations('abc',3))
---
[('a''b''c'), ('a''c''b'), ('b''a''c'), ('b''c''a'), ('c''a''b'), ('c''b''a')]

4) combinations 또는 combinations_with_replacement

조합 또는 중복 조합을 의미하는데 집합에서 일부 또는 전부의 원소를 가지고 부분집합을 만드는 것입니다. 이때 원소의 위치는 상관이 없게 됩니다. 

즉 (1,2) 와 (2, 1) 은 동일한 것으로 간주하며 중복 조합의 경우 원소가 한번 이상 부분집합에 포함이 될 수 있는 경우입니다.

1
2
3
4
5
6
7
8
from itertools import combinations
from itertools import combinations_with_replacement
 
print(list(combinations_with_replacement('12345'2)))
print(list(combinations('12345'2)))
---
[('1''1'), ('1''2'), ('1''3'), ('1''4'), ('1''5'), ('2''2'), ('2''3'), ('2''4'), ('2''5'), ('3''3'), ('3''4'), ('3''5'), ('4''4'), ('4''5'), ('5''5')]
[('1''2'), ('1''3'), ('1''4'), ('1''5'), ('2''3'), ('2''4'), ('2''5'), ('3''4'), ('3''5'), ('4''5')]
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter

5) 응용

join 과 sorted를 이용하면 문자열에 대한 부분집합도 쉽게 출력할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from itertools import combinations_with_replacement
 
print (*["".join(ch) for ch in combinations('12345'2)], sep='\n')
 
---
12
13
14
15
23
24
25
34
35
45
 
print (*["".join(ch) for ch in combinations(sorted('ZKAND'), 2)], sep='\n')
---
AD
AK
AN
AZ
DK
DN
DZ
KN
KZ
NZ
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter

6) 위키페이지

https://docs.python.org/2/library/itertools.html#itertools.groupby

 

9.7. itertools — Functions creating iterators for efficient looping — Python 2.7.16 documentation

 

docs.python.org