하루한줄 코딩일기
[Python] 순열(permutations)과 조합(combinations) 구현하기 본문
순열과 조합 구현하기
파이썬에서 하나의 리스트 내에서 조합할 수 있는 모든 경우의 수를 구하기 위해선 itertools 라이브러리의 permutations, combinations 함수를 활용할 수 있다.
순열(permutations)
순열(nPr)은 서로 다른 n개 중 r개를 중복 없이 뽑는 경우의 수를 말하며, 순서를 고려한다는 점에서 조합과 다르다.
즉, 순열에서는 (2,3)과 (3,2)를 다른 경우로 본다.
파이썬에서 리스트 arr이 주어질 때, 순서를 고려하여 2개의 요소를 뽑아 만들 수 있는 모든 조합의 경우는 다음과 같이 구할 수 있다. 이때, permutations() 함수는 기본적으로 itertools.permutations 타입을 반환하기 때문에 리스트로 변환하여 출력한다.
[참고] itertools.permutations - 순열
from itertools import permutations
arr = ['오렌지','자몽','사과']
per = list(permutations(arr, 2))
print(per)
>>> [('오렌지', '자몽'), ('오렌지', '사과'), ('자몽', '오렌지'), ('자몽', '사과'), ('사과', '오렌지'), ('사과', '자몽')]
조합(combinations)
조합(nCr)은 서로 다른 n개 중 r개를 중복 없이 뽑는 경우의 수를 말하며, 순서를 고려하지 않는다.
즉, 조합에서는 (2,3)과 (3,2)를 같은 경우로 본다.
파이썬에서 조합을 구현하는 방식은 위에서 순열을 구현한 방식과 동일하다. combinations() 함수는 순서를 고려하지 않기 때문에 ('오렌지', '자몽') 과 ('자몽', '오렌지') 는 동일한 케이스로 본다.
[참고] itertools.combinations - 조합
from itertools import combinations
arr = ['오렌지','자몽','사과']
com = list(combinations(arr, 2))
print(com)
>>> [('오렌지', '자몽'), ('오렌지', '사과'), ('자몽', '사과')]
'Languages. > Python' 카테고리의 다른 글
[Python] 정규표현식 re.sub을 이용한 문자열 치환하기 (0) | 2022.02.16 |
---|---|
[Python] TypeError: 'dict_values' object is not subscriptable (0) | 2022.02.02 |
[Python] input()과 sys.stdin.readline()의 차이 (0) | 2022.01.27 |
[Python] TypeError: 'int' object is not callable (0) | 2022.01.26 |
Comments