자료구조+알고리즘

순열, 조합

덕구공 2022. 3. 18. 08:20

itertools

  • 파이썬에서 itertools 라이브러리를 이용하여 매우 간편하게 순열, 조합, 중복순열, 중복조합을 구할 수 있다!

순열

  • 중복을 허용하지 않고 r개를 뽑힌 순서대로 나열한다.
  • 만약 (1, 2) (2, 1) 이 있다면 다른 경우의 수로 취급!
  • 튜플로 반환
from itertools import permutations

for i in permutations([1, 2, 2, 3], 2):
    print(i, end=" ")
    
// (1, 2) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 2)

 

조합

  • 중복을 허용하지 않고 r개를 뽑기만 한다
  • 만약 (1, 2) (2, 1)이 있다면 같은 경우의 수로 취급한다!
from itertools import combinations

for i in combinations([1, 2, 2, 3], 2):
    print(i, end=" ")

// (1, 2) (1, 2) (1, 3) (2, 2) (2, 3) (2, 3)

 

중복 조합은 아래 블로그 참고!

https://wotres.tistory.com/entry/python-%EC%88%9C%EC%97%B4-permutaions-%EC%A1%B0%ED%95%A9combinations-%EC%A4%91%EB%B3%B5%EC%88%9C%EC%97%B4-%EC%A4%91%EB%B3%B5%EC%A1%B0%ED%95%A9