-
파이썬 combinations 사용법 [python, 파이썬]알고리즘 2022. 5. 6. 18:55
조합을 만들어주는 combinations 함수 사용법 (파이썬)
combination 함수는 조합을 만들어주는 함수이다.
예를들어 [1,2,3,4] 가 있을 때 2 개를 뽑는 경우의 수를 만들어보면
[1,2], [1,3], [1,4], [2,3], [2,4], [3,4] 총 6가지가 존재한다. [4C2]
이러한 모든 경우를 dfs 를 사용해 직접 구할수도 있지만, 굳이 고생하지 말고 간편하게 combinations 을 사용할 수 있다.
사용법
1. 먼저 itertools 에서 combinations 를 임포트 해준다.
from itertools import combinations
2. combinations 함수를 사용한다
(!! 콤비네이션 함수의 반환값은 튜플이다)
from itertools import combinations original = [1, 2, 3, 4] for i in range(1, 5): combs = list(combinations(original, i)) print(combs) ```output [(1,), (2,), (3,), (4,)] [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] [(1, 2, 3, 4)] ```
'알고리즘' 카테고리의 다른 글
[Python] 팰린드롬 알고리즘 (Palindrome Algorithm) 설명 및 예제 (0) 2022.05.14 [python] 파이썬 Counter 함수 사용법 (0) 2022.05.06 A star 알고리즘 (python) 설명 (0) 2022.05.06 [LeetCode] Shortest Path in Binary Matrix 풀이 (Python) (0) 2022.05.06 [LeetCode] Backspace String Compare (0) 2022.05.04