파이썬/정리

순열과 조합 - Python

아몬드바 2023. 9. 10. 15:38
728x90

순열이 무엇일까?

- 주어진 n 개의 수에서 수를 뽑아 줄을 세울 수 있는 모든 경우의 수이다.

 

예시

- 5개의 카드중에서 3장을 뽑아 세 자리 숫자를 만드는 경우의 수

from itertools import combinations, permutations

nums = [1,2,3,4,5]
perm = list(permutations(nums, 3))

print(perm)
print(len(perm))
# [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 2), (1, 3, 4), (1, 3, 5), (1, 4, 2) ...
# 60

 

조합은 무엇일까?

- 주어진 리스트에서 r개의 값을 나열할 수 있는 경우의 수

from itertools import combinations, permutations

nums = [1,2,3,4,5]
perm = list(combinations(nums, 3))

print(perm)
print(len(perm))

# [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
728x90

'파이썬 > 정리' 카테고리의 다른 글

정규 표현식 - Python  (0) 2023.09.10
find vs index - Python  (0) 2023.09.10
람다함수(익명함수)  (0) 2023.09.10
진법 변환 함수  (0) 2023.07.26
Python deque  (0) 2023.07.04