순열, 조합 라이브러리

Hyun·2023년 6월 20일
0

파이썬

목록 보기
8/17

itertools 모듈 내의 순열, 조합을 구할 수 있는 4가지 함수에 대해 살펴보자.

4가지 함수가 반환하는 값들은 모두 클래스이므로 리스트 자료형으로 변환하여 사용한다.

순열

nPr, 순서있게 나열하는 방법이다.

중복을 허용하지 않는 경우

  • permutations 라이브러리 사용
  • 방법: permutaions(iterable, r): iterable 에서 원소 개수가 r 개인 순열 뽑기, r 을 지정하지 않거나 None으로 하면 최대 길이의 순열이 반환된다.

ex)

from itertools import permutations
arr = ["1", "2", "3"]

result = list(permutations(arr, 2))
print(result) 
# [('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]

result = list(permutations(arr))
print(result)
# [('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]

중복을 허용하는 경우

  • product 라이브러리 사용
  • 방법: product(iterables, repeat = r): 다른 함수와 달리 여러 iterable을 넣어줄 수 있고, 해당 iterable 간의 짝을 지어 반환한다.
from itertools import product

arr = ["1", "2", "3"]
result = list(product((arr), repeat = 2))
print(result)
# [('1', '1'), ('1', '2'), ('1', '3'), ('2', '1'), ('2', '2'), ('2', '3'), ('3', '1'), ('3', '2'), ('3', '3')]

arr1 = ["a", "b"]
arr2 = [1, 2]
result = list(product(arr1, arr2, repeat = 1))
print(result)
# [('a', 1), ('a', 2), ('b', 1), ('b', 2)]

조합

nCr, 순서를 따지지 않고 나열하는 방법이다.

예를 들어 순열은 ('1', '2') 와 ('2', '1') 이 다르게 취급되지만 조합의 경우 순서를 따지지 않기 때문에 ('1', '2') 와 ('2', '1') 이 동일하게(하나로) 취급된다.

중복을 허용하지 않는 경우

  • combinations 라이브러리 사용
  • 방법: combinations(iterable, r): iterable 에서 원소 개수가 r 개인 조합 뽑기

ex)

from itertools import combinations

arr1 = ["1", "2", "3"]
result = list(combinations(arr1, 2))
print(result) 
# [('1', '2'), ('1', '3'), ('2', '3')]

arr2 = ["-1", "0", "1", "-1"] # 삼총사 문제에서 사용됨
result = list(combinations(arr2, 3))
print(result)
# [('-1', '0', '1'), ('-1', '0', '-1'), ('-1', '1', '-1'), ('0', '1', '-1')]

중복을 허용하는 경우

  • combinations_with_replacement 라이브러리 사용
  • 방법: combinations_with_replacement(iterable, r): iterable 에서 중복을 하용하여 원소 개수가 r 개인 조합 뽑기
from itertools import combinations_with_replacement

arr1 = ["1", "2", "3"]
result = list(combinations_with_replacement(arr1, 2))
print(result)
# [('1', '1'), ('1', '2'), ('1', '3'), ('2', '2'), ('2', '3'), ('3', '3')]

arr2 = ["-1", "0", "1", "-1"]
result = list(combinations_with_replacement(arr2, 3))
print(result)
# [('-1', '-1', '-1'), ('-1', '-1', '0'), ('-1', '-1', '1'), ('-1', '-1', '-1'), ('-1', '0', '0'), ('-1', '0', '1'), ('-1', '0', '-1'), ('-1', '1', '1'), ('-1', '1', '-1'), ('-1', '-1', '-1'), ('0', '0', '0'), ('0', '0', '1'), ('0', '0', '-1'), ('0', '1', '1'), ('0', '1', '-1'), ('0', '-1', '-1'), ('1', '1', '1'), ('1', '1', '-1'), ('1', '-1', '-1'), ('-1', '-1', '-1')]
profile
better than yesterday

0개의 댓글