# [Python] 순열과 조합 라이브러리

최더디·2021년 2월 10일
1

## 📌 순열과 조합 라이브러리

### 1. 순열(permutations)

permutations(반복 가능한 객체, n) // n=몇개를 뽑을 것인지

• 중복을 허용하지 않는다.
• 순서에 의미가 있다 (= 같은 값이 뽑히더라도 순서가 다르면 다른 경우의 수로 판단)
from itertools import permutations

print(list(permutations([1,2,3,4], 2)))
print(list(permutations([1,2,3,1], 2)))

# result1
# [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

# result2
# [(1, 2), (1, 3), (1, 1), (2, 1), (2, 3), (2, 1), (3, 1), (3, 2), (3, 1), (1, 1), (1, 2), (1, 3)]

### 2. 중복 순열(product)

product(반복 가능한 객체, repeat=num)

• 중복을 허용하는 순열
from itertools import product

print(list(product([1,2,3,4], repeat=2)))
print(list(product([1,2,3,1], repeat=2)))

# result1
# [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]

# result2
# [(1, 1), (1, 2), (1, 3), (1, 1), (2, 1), (2, 2), (2, 3), (2, 1), (3, 1), (3, 2), (3, 3), (3, 1), (1, 1), (1, 2), (1, 3), (1, 1)]

### 3. 조합(combinations)

combinations(반복 가능한 객체, n) // n=몇개를 뽑을 것인지

• 중복을 허용하지 않는다.
• 순서에 의미가 없다 (= 같은 값이 뽑히면 같은 경우의 수로 판단)
from itertools import combinations

print(list(combinations([1,2,3,4], 2)))
print(list(combinations([1,2,3,1], 2)))

# result1
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

# result2
# [(1, 2), (1, 3), (1, 1), (2, 3), (2, 1), (3, 1)]

### 4. 중복 조합(combinations_with_replacement)

combinations_with_replacement(반복 가능한 객체, n) // n=몇개를 뽑을 것인지

• 중복을 허용하는 조합
from itertools import combinations_with_replacement

print(list(combinations_with_replacement([1,2,3,4], 2)))
print(list(combinations_with_replacement([1,2,3,1], 2)))

# result1
# [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]

# result2
# [(1, 1), (1, 2), (1, 3), (1, 1), (2, 1), (2, 2), (2, 3), (2, 1), (3, 1), (3, 2), (3, 3), (3, 1), (1, 1), (1, 2), (1, 3), (1, 1)]
focus on why