본문 바로가기

Dev/Python

[Python] 순열, 조합, 곱집합

순열(permutation)

  • 순서를 정해 나열한 경우의 수
  • itertools.permutations을 이용
  • permutations(arr, n) 에서 n개의 원소를 골라 순서를 정해 나열한다는 뜻
import itertools

a = ['a','b','c']
b = [1,2,3]

print(list(itertools.permutations(a)))
# [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

print(list(itertools.permutations(b, 2)))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

 

조합(combination)

  • 서로 다른 n개 중에서 r개를 선택하는 경우의 수
  • itertools.combinations를 사용
  • 조합은 ('a','b')와 ('b','a')를 같은 값으로 구분
import itertools

a = ['a','b','c']
b = [1,2,3]

print(list(itertools.combinations(a, 2)))
# [('a', 'b'), ('a', 'c'), ('b', 'c')]

 

곱집합(cartesian product)

  • 여러 집합들 간에 하나씩 뽑아 조합을 만들 수 있는 모든 수
  • itertools.product를 이용하면 for문을 사용하지 않고 곱집합을 구할 수 있음
import itertools

a = ['a','b','c']
b = [1,2,3]

print(list(itertools.product(a, b)))
# [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]
반응형

'Dev > Python' 카테고리의 다른 글

[Python] terminal에서 Python console 지우기  (0) 2021.07.03
[Python] counter  (0) 2021.06.15
[Python] 문자열 합치기 - join  (0) 2021.06.15
[Python] zip  (0) 2021.06.15
[Python] 알파벳 출력하기 - string 모듈  (0) 2021.06.15