Python

python - combinations 함수

SS_G 2023. 3. 13. 23:27
반응형

 

itertools 모듈에서 제공하는 함수 중 하나인 combinations 함수에 대해 설명드리겠습니다.

combinations 함수는 주어진 iterable에서 r의 길이를 가진 가능한 모든 조합을 반환하는 역할을 합니다.

사용법

from itertools import combinations

array = [int(input()) for _ in range(9)]

for i in itertools.combinations(array, 7):
	print(i)

combinations(iterable, r) => 이 함수는 iterable한 자료형에서 원소의 개수가 r인 모든 조합을 생성합니다.

예를 들어, array 리스트가 9개의 입력값, 즉 [1, 2, 3, 4, 5, 6, 7, 8, 9]를 받았다고 가정해 봅시다.

이 경우 9개의 인덱스 값 중에서 7개를 뽑는 모든 경우의 수를 생성해냅니다. 그 결과 print(i)는 (1, 2, 3, 4, 5, 6, 7), (1, 2, 3, 4, 5, 6, 8), (1, 2, 3, 4, 5, 6, 9) 등, 모든 조합을 튜플 형태로 출력하게 됩니다.


from itertools import combinations

# 리스트에서 2개씩 가능한 모든 조합 생성
my_list = [1, 2, 3, 4]
combinations_list = list(combinations(my_list, 2))

print(combinations_list)
# 출력: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

'combinations(my_list, 2)'는 'my_list'에서 두 개씩 가능한 모든 조합을 생성하고, 이를 'list' 함수를 통해 리스트로 변환하여 'combinations_list' 변수에 저장합니다.

'combinations' 함수는 iterable에서 가능한 조합을 생성할 때 중복되는 조합을 생성하지 않는 것이 특징입니다. 예를 들어 '(1, 2)'와 '(2, 1)'은 서로 다른 튜플이지만, 이 두 개의 튜플은 같은 조합으로 간주됩니다.

이는 'combinations' 함수가 생성하는 조합에서 순서가 중요하지 않다는 점을 보여줍니다. 예컨대 'combinations([2, 3], 2)' 함수는 '(2, 3)'와 '(3, 2)' 두 개의 튜플이 아닌, 하나의 튜플인 '(2, 3)'만을 생성합니다.

중복된 조합도 생성하고 싶을 때는 'combinations_with_replacement' 함수를 사용하시면 됩니다. 예를 들어, 'combinations_with_replacement([2, 3], 2)' 함수는 '(2, 2)', '(2, 3)', '(3, 3)' 세 개의 튜플을 생성합니다.

많은 도움이 되셨기를 바랍니다.

 

 

https://docs.python.org/ko/3/library/itertools.html

 

itertools — Functions creating iterators for efficient looping

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...

docs.python.org

 

반응형

'Python' 카테고리의 다른 글

Python 함수 정리(계속 업데이트 예정)  (0) 2023.03.22
if__name__ == '__main__'  (1) 2023.01.31