자바스크립트를 사용하면 순열과 조합을 구하는 코드를 직접 작성해야 하는데요,
파이썬을 사용하면 모듈을 통해 쉽게 구할 수 있어서 상당히 편리합니다.
이번에는 파이썬에서 순열과 조합을 쉽게 구할 수 있도록 도와주는 itertools 모듈에 대해 알아보겠습니다.
순열
permutations(iterable, r)
from itertools import permutations
a = [1, 2, 3, 4]
permus = list(permutations(a, 2))
permus
# [(1, 2), (1, 3), (1, 4),
# (2, 1), (2, 3), (2, 4),
# (3, 1), (3, 2), (3, 4),
# (4, 1), (4, 2), (4, 3)]
itertools 모듈의 permutations 클래스를 사용하면 순열을 구할 수 있습니다.
인자로는 이터러블 객체(iterable)와 선택할 원소의 개수(r)를 전달합니다.
위 코드는 서로 다른 4개의 원소에서 2개를 선택해 순서를 고려해 나열한 모든 경우의 수를 보여줍니다.
중복은 허용하지 않습니다.
조합
combinations(iterable, r)
from itertools import combinations
b = [1, 2, 3, 4, 5]
combis = list(combinations(b, 3))
combis
# [(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)]
itertools 모듈의 combinations 클래스를 사용하면 조합을 구할 수 있습니다.
인자로는 이터러블 객체(iterable)와 선택할 원소의 개수(r)를 전달합니다.
위 코드는 서로 다른 5개의 원소에서 순서를 고려하지 않고 3개의 원소를 선택하는 경우의 수를 보여줍니다.
중복은 허용하지 않습니다.
중복순열
product(*iterables, repeat)
from itertools import product
arr = [['a', 'b', 'c'], ['d', 'e', 'f']]
list(product(*arr))
# [('a', 'd'), ('a', 'e'), ('a', 'f'),
# ('b', 'd'), ('b', 'e'), ('b', 'f'),
# ('c', 'd'), ('c', 'e'), ('c', 'f')]
itertools 모듈의 product 클래스를 사용하면 중복순열을 구할 수 있습니다.
인자로 이터러블 객체들(*iterables)을 전달합니다.
중복조합
combinations_with_replacement(iterable, r)
from itertools import combinations_with_replacement
a = [1, 2, 3, 4, 5]
list(combinations_with_replacement(a, 2))
# [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
# (2, 2), (2, 3), (2, 4), (2, 5),
# (3, 3), (3, 4), (3, 5),
# (4, 4), (4, 5),
# (5, 5)]
itertools 모듈의 combinations_with_replacement 클래스를 사용하면 중복조합을 구할 수 있습니다.
인자로 이터러블 객체(iterable)와 선택할 원소의 개수(r)를 전달합니다.
'파이썬・ML' 카테고리의 다른 글
파이썬 random 모듈 사용하기 (0) | 2023.06.14 |
---|---|
파이썬 객체에 대해서 (0) | 2023.06.05 |
파이썬 숫자 판별하는 문자열 함수(isdecimal, isdigit, isnumeric) (0) | 2023.06.01 |
파이썬 datetime 모듈 사용해서 요일 알아내기 (0) | 2023.06.01 |
파이썬 enumerate 내장함수 사용하기 (0) | 2023.05.31 |