파이썬
[Python] 순열 / 조합
이진지니지니진
2023. 2. 16. 23:14
- 순열
서로 다른 n개에서 서로 다른 r개를 선택하여 일렬로 나열하는 것
nPr = n! / (n-r)!
- 조합
서로 다른 n개에서 순서 상관없이 서로 다른 r개를 선택하는 것
nCr = n! / r! * (n-r)!
순열이랑 조합 .. 고등학생 때(?) 배웠을 때는 분명 어렵지 않았는데 다시 보니 매우 낯설고 헷갈린다 😳 |
<순열>
from itertools import permutations
data = [1, 2, 3]
result = list(permutations(data, 3)) #모든 순열 구하기
print(result) #[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
<중복 허용된 순열>
from itertools import product
data = [1, 2, 3]
result = list(product(data, repeat=2)) #2개를 뽑는 모든 순열 구하기(중복 허용)
print(result) #[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
<조합>
from itertools import combinations
data = [1, 2, 3]
result = list(combinations(data, 2)) #2개를 뽑는 모든 조합 구하기
print(result) #[(1, 2), (1, 3), (2, 3)]
<중복 허용된 조합>
from itertools import combinations_with_replacement
data = [1, 2, 3]
result = list(combinations_with_replacement(data, 2)) #2개를 뽑는 모든 조합 구하기(중복 허용)
print(result) #[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
이것은 그냥 외워야 할 것들 .. 아쟈쟈쟈쟈쟈쟈쟈 쟈쟈쟈쟈쟈쟈쟈쟈 😤 |