☑️ 순열 : 서로 다른 n개의 원소에서 r개를 중복없이 순서에 상관있게 선택하는 것
☑️ 조합 : 서로 다른 n개에서 순서와 상관없이 r개를 고르는 것
✔️ 중복 순열
- from itertools import product
from itertools import product
for i in product([1, 2, 3], 'ab'):
print(i, end=" ")
# (1, 'a') (1, 'b') (2, 'a') (2, 'b') (3, 'a') (3, 'b')
for i in product([1, 2, 3], repeat=2):
print(i, end=" ")
# (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3)
✔️ 중복 조합
- from itertools import combinations_with_replacement
from itertools import combinations_with_replacement
for i in combinations_with_replacement([1, 2, 3, 4], 2):
print(i, end=" ")
# (1, 1) (1, 2) (1, 3) (1, 4) (2, 2) (2, 3) (2, 4) (3, 3) (3, 4) (4, 4)
이처럼 Python의 경우 itertools 패키지를 통해 순열과 조합을 쉽게 구현할 수 있음
이번엔 이 순열 패키지 사용과 직접 구현 두 가지 코드로 풀어보기로 함
코드트리 | 코딩테스트 준비를 위한 알고리즘 정석
국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.
www.codetree.ai
(1) 순열 패키지 사용
from itertools import product
nums = []
k, n = map(int, input().split())
for i in range(1, k+1):
nums.append(i)
for i in product(nums, repeat=n):
for j in i:
print(j, end=" ")
print()
(2) 직접 구현
def arr_print():
for i in nums:
print(i, end=" ")
print()
def perm(idx):
if idx == n+1:
arr_print()
return
for i in range(1, k+1):
nums.append(i)
perm(idx+1)
nums.pop()
nums = []
k, n = map(int, input().split())
perm(1)
[코드트리/INTERMEDIATE LOW] Simulation 1차원 바람 Python 파이썬 (0) | 2023.08.07 |
---|---|
[코드트리/INTERMEDIATE LOW] DP I 사각형 채우기 Python 파이썬 (0) | 2023.08.04 |
[코드트리/INTERMEDIATE LOW] DP I 계단 오르기 Python (0) | 2023.08.03 |
[코드트리/INTERMEDIATE LOW] Simulation 양수 직사각형 최대 크기 Python (0) | 2023.08.02 |
[코드트리/INTERMEDIATE LOW] Simulation 금 채굴하기 Python (0) | 2023.07.31 |