조합, 순회, 소수 문제

Leejaegun·2025년 3월 12일

코딩테스트 시리즈

목록 보기
4/49
post-thumbnail

itertools 라이브러리 정리: combinations, permutations, product, combinations_with_replacement

Python의 itertools 라이브러리는 조합과 순열을 비롯해 다양한 경우의 수를 다룰 수 있는 기능을 제공한다.
여기에서는 combinations, permutations, product, combinations_with_replacement의 차이를 정리한다.

1. combinations() (조합)

  • 순서 상관없이 n개 중 r개를 선택.
  • 같은 원소의 조합은 한 번만 등장함.
    즉, (a, b)와 (b, a)는 같은 것으로 간주됨.

예제 코드

from itertools import combinations

arr = [3, 1, 6, 4]
for items in combinations(arr, 2):  # 2개씩 조합 생성
    print(items)

📌 출력

(3, 1)
(3, 6)
(3, 4)
(1, 6)
(1, 4)
(6, 4)

2. permutations() (순열)

순서를 고려하여 n개 중 r개를 선택.
(a, b)와 (b, a)는 다른 경우로 취급됨.

from itertools import permutations

arr = [3, 1, 6, 4]
for items in permutations(arr, 2):  # 2개씩 순열 생성
    print(items)

📌 출력

(3, 1)
(3, 6)
(3, 4)
(1, 3)
(1, 6)
(1, 4)
(6, 3)
(6, 1)
(6, 4)
(4, 3)
(4, 1)
(4, 6)

3. product() (중복 순열, 데카르트 곱)

중복을 허용하면서 순서를 고려하여 n개 중 r개를 선택.
즉, (a, b)와 (b, a)는 다르며, 자기 자신을 포함한 경우도 가능.

from itertools import product

arr = [3, 1, 6]
for items in product(arr, repeat=2):  # 2개씩 중복 순열 생성
    print(items)
📌 출력
(3, 3)
(3, 1)
(3, 6)
(1, 3)
(1, 1)
(1, 6)
(6, 3)
(6, 1)
(6, 6)

✔ product(arr, repeat=2) → arr에서 2개를 뽑고 중복을 허용.

4. combinations_with_replacement() (중복 조합)

순서는 고려하지 않지만, 같은 원소를 중복 선택할 수 있음.
(a, a), (a, b), (b, b) 같은 조합이 나올 수 있음.

from itertools import combinations_with_replacement

arr = [3, 1, 6]
for items in combinations_with_replacement(arr, 2):  # 2개씩 중복 조합 생성
    print(items)

📌 출력

(3, 3)
(3, 1)
(3, 6)
(1, 1)
(1, 6)
(6, 6)

✔ combinations_with_replacement(arr, 2) → 중복을 허용하지만 순서는 고려하지 않음.

🚀 정리: combinations, permutations, product, combinations_with_replacement 차이점

함수설명특징
combinations(arr, r)조합 (순서 X, 중복 X)(a, b)(b, a)는 같음
permutations(arr, r)순열 (순서 O, 중복 X)(a, b)(b, a)는 다름
product(arr, repeat=r)중복 순열 (순서 O, 중복 O)(a, a), (a, b), (b, a) 가능
combinations_with_replacement(arr, r)중복 조합 (순서 X, 중복 O)(a, a), (a, b), (b, b) 가능

✅ combinations() → 순서 X, 중복 X
✅ permutations() → 순서 O, 중복 X
✅ product() → 순서 O, 중복 O
✅ combinations_with_replacement() → 순서 X, 중복 O

profile
Lee_AA

0개의 댓글