순열
순서대로 뽑아내는 것이며, 수학에서 nPr과 동일합니다.
from itertools import permutations
arr = ['a','b','c']
print(permutations(arr))
arr를 a,b,c 로 이루어진 문자배열이라고 했을때,
arr를 permutation하여 출력하면

다음과 같이 내부를 알 수 없는 객체 형식으로 출력되기 때문에
list로 변환해주는 작업을 거쳐야 합니다.
from itertools import permutations
arr = ['a','b','c']
print(list(permutations(arr)))

다음과 같이 순서가 적용 된 순열이 출력됨을 확인할 수 있습니다.
이것을 'abc', 'acb'형식의 문자열로 출력하고 싶다면
from itertools import permutations
arr = ['a','b','c']
print(list(map(''.join,permutations(arr))))
.join으로 문자열로 붙여주면 됩니다!
from itertools import permutations
arr = ['a','b','c']
print(list(map(''.join,permutations(arr,2))))

다음과 같은 결과가 나왔습니다.
또한, 몇 개만 뽑아 순열을 만들고 싶을때 permutations(arr,2) 이렇게 뽑고 싶은 갯수를 넣어주면 됩니다!
조합 (Combinations)
순서 상관없이 n개중 r개를 뽑았을 경우이며, 수학에서 nCr과 같습니다.
from itertools import combinations
arr = ['a','b','c']
print(list(combinations(arr,2)))

이런 결과가 나옵니다
순열처럼 .join으로 문자열로 붙여보겠습니다
from itertools import combinations
arr = ['a','b','c']
print(list(map(''.join,combinations(arr,2))))

순열과 조합 결과 비교
순열과 조합의 개념을 설명하며 예로 들었던 3개의 문자 중에 2개를 뽑아 문자열를 만드는 경우를 코드와 출력결과를 통해 살펴보겠습니다.
순열 코드
from itertools import permutations
arr = ['a','b','c']
print(list(map(''.join,permutations(arr,2))))
조합 코드
from itertools import combinations
arr = ['a','b','c']
print(list(combinations(arr,2)))
순열 결과

조합 결과

결론
출력결과를 보시면 순열과 조합의 차이를 명확하게 아실 수 있습니다.
순열은 순서대로 나열하기 때문에 'ab'와 'ba'는 다른 케이스로 봅니다.
하지만 조합은 뽑기만 하기 때문에 'ab'와 'ba'는 같은 케이스로 구분하게 됩니다.
그래서 'ab'만 결과에 나오게 됩니다.
'🧮Programming > Python' 카테고리의 다른 글
| [Python] 입력 값 다중 리스트로 만드는 법 (0) | 2024.02.13 |
|---|---|
| [Python] 람다(lambda)함수 (0) | 2024.02.12 |
| [Python] 정렬 함수 (0) | 2024.02.11 |
| [Python] map함수 (1) | 2024.02.09 |
| [Python] join함수 (0) | 2024.02.08 |