[파이썬을 파이썬답게] 순열과 조합(combinations, permutations)

이상해씨·2024년 2월 8일
0

Python

목록 보기
12/21

순열과 조합

순열(permutations)

📌 순열
: 주어진 요소들을 재배열하여 만들 수 있는 모든 조합을 의미. 순서가 결과에 영향을 미치며, 중복은 허락하지 않음.

itertools.permutations(iterable, r=None)

  • iterable: 순열을 생성할 대상이 되는 이터러블(예: 리스트, 문자열 등).
  • r: 선택적 매개변수로, 순열을 생성할 때 사용할 요소의 개수를 지정. r이 지정되지 않으면 iterable의 길이가 사용됨.
import itertools

pool = ['A', 'B', 'C']
print(list(map(''.join, itertools.permutations(pool)
))) # 3개의 원소로 순열 만들기
print(list(map(''.join, itertools.permutations(pool, 2)))) # 2개의 원소로 순열 만들기

정렬
sorted(itertools.permutations())을 하면 숫자 순서대로 정렬이 됨

조합(combinations)

📌조합
: 특정 집합에서 일부 요소를 순서에 상관없이 선택하는 방법

itertools.combinations(iterable, r)
  • iterable: 조합을 생성할 대상이 되는 이터러블(예: 리스트, 문자열 등).
  • r: 조합을 생성할 때 선택될 요소의 개수.
from itertools import combinations

data = [1, 2, 3]
for combo in combinations(data, 2):
    print(combo)
  • 문자열
from itertools import combinations

data = 'ABC'
for combo in combinations(data, 2):
    print(''.join(combo))

참고

profile
공부에는 끝이 없다

0개의 댓글