파이썬 내장 라이브러리인 itertools는 자신만의 반복자를 효율적으로 만들 수 있게 해주는 모듈이 담긴 라이브러리다.

itertools 모듈 안에는 combinations, permutations 등 여러 유용한 함수가 들어있어, for문이나 while문 없이 효율적으로 loop를 돌게 할 수 있다.

예시 코드 1) permutations 함수는 조합 가능한 모든 경우를 set 형식으로 '순서대로' 반환한다.

1
2
3
4
from itertools import permutations # permutations 함수는 수열을 구할 때 사용한다
pool = ['A''B''C']
print(list(map(''.join, permutations(pool)))) # 3개 원소로 수열 만들기
print(list(map(''.join, permutations(pool, 2)))) # 2개 원소로 수열 만들기 
cs


예시 코드 2) combinations 함수는 permutations 함수와 유사하지만, 순서를 보장하지 않는다.


1
2
3
from itertools import combinations
for c in combinations([1, 2, 3, 4], 2):
    print(c)


itertools 모듈은 브루트 포스 알고리즘 문제에 자주 등장한다.



참고한 글 :

Python(파이썬) 기본 - 40. itertools 모듈과 iterable에 유용한 내장함수 / Suwoni-Codelab
순열과 조합 - combinations, permutations / 프로그래머스