코딩 교훈 기록
파이썬 조합 관련 itertools 라이브러리
Disciple428
2025. 4. 22. 20:41
✅ itertools.combinations
📌 정의
itertools.combinations(iterable, r)
→ iterable에서 r개를 뽑는 조합을 구해줌
→ 중복 없이, 순서 상관 없음
✅ 예제 코드
from itertools import combinations
data = ['a', 'b', 'c']
result = list(combinations(data, 2))
print(result)
출력:
[('a', 'b'), ('a', 'c'), ('b', 'c')]
✔️ a-b, a-c, b-c 조합만 나옴
✔️ b-a, c-a는 포함되지 않음 (순서 없음)
✅ 관련 함수들 정리
함수명 | 설명 | 예시 결과 |
combinations(iter, r) | 중복 없이 r개 조합 | ('a','b'), ('a','c') |
permutations(iter, r) | 순열, 순서 중요 | ('a','b'), ('b','a') |
combinations_with_replacement(iter, r) | 중복 허용 조합 | ('a','a'), ('a','b') |
product(iter, repeat=r) | 중복 순열, 데카르트 곱 | ('a','a'), ('a','b') |
✅ 조합 수만 구하고 싶다면?
파이썬 math 모듈을 사용하면 쉽게 계산 가능:
from math import comb # Python 3.8 이상
print(comb(5, 2)) # 10
만약 Python < 3.8 이라면 factorial()로 직접 계산:
from math import factorial
def nCr(n, r):
return factorial(n) // (factorial(r) * factorial(n - r))
print(nCr(5, 2)) # 10
✅ 실전 예제: 부분 집합 구하기 (조합 응용)
from itertools import combinations
arr = [1, 2, 3, 4]
for r in range(1, len(arr) + 1):
for subset in combinations(arr, r):
print(subset)
✔️ 결과: [1], [2], [1,2], ..., [1,2,3,4] 등 모든 조합 출력
✅ 정리 요약표
기능 | 방법 | 설명 |
r개 조합 생성 | combinations(data, r) | 중복 X, 순서 X |
순열 생성 | permutations(data, r) | 중복 X, 순서 O |
중복 조합 | combinations_with_replacement(data, r) | 중복 O, 순서 X |
중복 순열 | product(data, repeat=r) | 중복 O, 순서 O |
조합 수 계산 | math.comb(n, r) or 직접 구현 | 조합 수만 구할 때 사용 |