Development/Language

순열, 조합, 중복순열

비완 2022. 12. 29. 17:37
반응형

python에서 순열, 조합등을 구현하려면 제법 귀찮게 코드를 작성하여야 한다.
그런데 찾아보니 외부 라이브러리를 통해 간단히 구현할 수 있어, 정리해보려 한다.

1. 순열(Permutaion)

from itertools import permutations

nums = [1, 2, 3]
permute = permutations(nums, 2)
print(list(permute))
[(1,2), (1,3), (2,1), (2,3), (3,1), (3,2)]

 

2. 조합(Combination)

from itertools import combinations

nums = [1, 2, 3]
combination = combinations(nums, 2)
print(list(combination))
[(1,2), (1,3), (2,3)]

 

3. 중복순열(Product)

from itertools import product

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

 

눈치챘겠지만, 구현은 거의 동일하다.

백준 온라인 코딩에서 백트래킹 관련 문제를 풀다 발견해서 정리해두었다.

 

추가로 중복이 허용되는 경우에는 아래와 같이 구현이 가능하다.

 

중복허용조합

from itertools import combinations_with_replacement

nums = [1, 2, 3]
prod = combinations_with_replacement(nums, 2)
print(list(prod))
[(1,1), (1,2), (1,3), (2,2), (2,3), (3,3)]
반응형

'Development > Language' 카테고리의 다른 글

[Java] 원격파일 유효여부 체크  (0) 2024.03.06
Python 반올림 오류 해결  (0) 2020.04.30
빈값 체크  (0) 2019.10.31
HttpClient timeout 설정  (0) 2019.10.14
문자열 중복 찾기  (0) 2019.09.26