상세 컨텐츠

본문 제목

순열과 조합 [파이썬]

파이썬

by 덴마크 당나귀 2022. 8. 5. 17:44

본문

728x90

순열 : 서로 다른 n개에서 서로 다른 r개를 선택하여 일렬로 나열하는 것.

예) {'A','B','C'} 에서 세 개를 선택하여 나열하는 경우: 'ABC', 'ACB','BAC','BCA','CAB' 나열 하는것

 

이 경우 itertools 에서 permutations를 사용하면 되는데 코드로 보면

from itertools import permutations

data = ['a','b','b','d']
temp = []
result = list(permutations(data,3))

print(result)

 

이런 식으로 사용 하면 된다.

 

조합 : 서로 다른 n개에서 순서에 상관 없이 서로 다른 r개를 선택하는 것이다. 

{A,B,C}에서 순서를 고려하지 않고 두개를 뽑는 경우 :'AB', 'AC', 'BC'

 

이 경우에는 itertools 에서 combinations를 사용하면 되는데 코드로 보면

from itertools import combinations

data = ['a','b','b','d']
result = list(combinations(data,2))
print(result)

 

이런식으로 코드를 짤 수 있다.

 

두 코드의 차이를 보면 아래 코드를 통해 확인 할 수 있는데,

 

from itertools import combinations
from itertools import permutations

data = ['a','b','b','d']
d = ['a','b','b','d']
result = list(combinations(data,2))
r = list(permutations(d,2))
print(result)
print(r)

 

두 가지를 같이 사용할 경우 결과 값은

[('a', 'b'), ('a', 'b'), ('a', 'd'), ('b', 'b'), ('b', 'd'), ('b', 'd')]
[('a', 'b'), ('a', 'b'), ('a', 'd'), ('b', 'a'), ('b', 'b'), ('b', 'd'), ('b', 'a'), ('b', 'b'), ('b', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'b')]

이렇게 나온다. 

차이는 보면 알겠지만, 중복의 유무이다.

728x90

관련글 더보기