language/python

[파이썬/python] 순열(permutations)과 조합(combinations)

moonsun623 2021. 10. 3. 19:40
반응형

순열

서로 다른 n개 중 r개를 뽑아 순서를 고려하여 경우의 수를 나열 

nPr의 형태로 표현한다.

ex ) ['가','나','다','라'] 중 1등, 2등을 뽑는 방법은 아래와 같다.

['가' '나'] /['가' '다']/['가' '라']

['나' '가'] /'[나' '다']/'[나' '라']

['다' '가'] /['다' '나']/['다' '라']

['라' '가'] /['라' '나']/['라' '다']

 

조합

서로 다른 n개 중 r개를 뽑아 순서를 고려하지않고 경우의 수를 나열 

nCr의 형태로 표현한다.

ex ) ['가','나','다','라'] 중 2개를 뽑는 방법은 아래와 같다.

['가' '나'] /['가' '다']/['가' '라']

'[나' '다']/'[나' '라']

['다' '라']

 

파이썬에서 순열(permutations)과 조합(combinations)

직접 순열, 조합을 만드는 함수를 코드로 짜도 되지만,

파이썬은 itertools 모듈에서 순열과 조합 메소드를 지원한다.

from itertools import permutations,combinations
arr=[1,4,10,15]
print(list(permutations(arr,2)))
#[(1, 4), (1, 10), (1, 15), (4, 1), (4, 10), (4, 15), (10, 1), (10, 4), (10, 15), (15, 1), (15, 4), (15, 10)]
print(list(combinations(arr,2)))
#[(1, 4), (1, 10), (1, 15), (4, 10), (4, 15), (10, 15)]

permutations 메소드와 combinations 메소드는 "객체"를 반환하기 때문에

내용을 프린트 하고 싶을땐 iterable객체로 변환 후 출력해야한다.

 

중복 순열 (product)

순열 중 중복을 허용하는 순열이다.

두개 이상 리스트의 순열을 구할 때 사용된다.

 

product(A,B)=  ((x,y) for x in A for y in B) 

from itertools import product
arr=[1,4,8]
print(list(product(arr,"xy")))
#[(1, 'x'), (1, 'y'), (4, 'x'), (4, 'y'), (8, 'x'), (8, 'y')]

repeat 을 사용해 한 객체 원소 간 순열을 만들 수 도 있다. 

product(A, repeat=2) =product(A, A)

from itertools import product
arr=[1,4,8]
print(list(product(arr,repeat=2)))
#[(1, 1), (1, 4), (1, 8), (4, 1), (4, 4), (4, 8), (8, 1), (8, 4), (8, 8)]

 

 

중복 조합 (combinations_with_replacement)

조합 중 중복을 허용하는 조합이다.

combinations_with_replacement(iter객체,원소개수)

from itertools import combinations_with_replacement
arr=[1,4,8]
print(list(combinations_with_replacement(arr,2)))
#[(1, 1), (1, 4), (1, 8), (4, 4), (4, 8), (8, 8)]

 

'language > python' 카테고리의 다른 글

프로그래머스 하노이의 탑 (파이썬 풀이)  (0) 2021.10.15
파이썬 힙(heapq) 모듈  (0) 2021.09.30
파이썬 내장함수 map  (0) 2021.09.03