Python itertools 라이브러리 조합/순열

고승우·2023년 4월 5일
0
post-thumbnail

itertools 라이브러리란?

효율적인 루핑을 위한 이터레이터를 만드는 함수. 자체적으로 혹은 조합하여 유용한 빠르고 메모리 효율적인 도구의 핵심 집합을 표준화한다. 이 중에서 자주 쓰이는 조합순열에 대해 정리해보려고 한다.

itertools.combinations(p, r)

반복되는 요소가 없는 정렬된 순서의 r-길이 튜플들을 반환.

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

결과

(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)

itertools.permutations(p, r)

반복되는 요소가 없는 정렬된 순서의 r-길이 튜플들을 반환.

from itertools import permutations
a = [1, 2, 3]
for i in permutations(a, 3):
    print(i)

결과

(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

itertools.combinations_with_replacement(p, r)

반복되는 요소가 있는 정렬된 순서의 r-길이 튜플들을 반환.

from itertools import combinations_with_replacement
a = [1, 2, 3]
for i in combinations_with_replacement(a, 3):
    print(i)

결과

(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 2)
(1, 2, 3)
(1, 3, 3)
(2, 2, 2)
(2, 2, 3)
(2, 3, 3)
(3, 3, 3)

profile
٩( ᐛ )و 

0개의 댓글