Programming/Python

[Python] 파이썬 순열과 조합

owls 2022. 5. 17. 17:21
728x90

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

     {'A', 'B', 'C'}에서 3개를 선택하여 나열하는 경우 

     -> 'ABC', 'ACB', 'BAC', BCA', 'CAB', 'CBA'

     순열의 수 : nPr = n * (n-1)*(n-2)* ... * (n-r+1)

 

* 조합 : 서로 다른 n개에서 순서에 상관 없이 서로 다른 r개를 선택 

     {'A', 'B', 'C'}에서 순서를 고려하지 않고 두 개 선택하는 경우

     -> 'AB', 'AC', 'BC'

     조합의 수 : nCr =  ( n*(n-1)*(n-2)* ... * (n-r+1) ) / r!

                   

 

          

1. 순열 - 순서 o

#순열
from itertools import permutations
data = ['A', 'B', 'C']
result = list(permutations(data, 3)) #3자리의 모든 순열 
print(result)

 

2. 조합 - 순서 X

#조합
from itertools import combinations
data = ['A', 'B', 'C']
result = list(combinations(data, 2)) #2개를 뽑는 모든 조합
print(result)

 

3. 중복 순열

#중복 순열
from itertools import product
data = ['A', 'B' , 'C']
result = list(product(data, repeat=2)) #2개를 뽑는 모든 순열 구하기 ( 중복 허용)
print(result)

 

4. 중복 조합

#중복 조합
from itertools import combinations_with_replacement
data = ['A', 'B', 'C']
#2개를 뽑는 모든 조합 구하기(중복허용)
result = list(combinations_with_replacement(data,2))
print(result)

 

5. Counter: 등장 횟수 세는 기능

리스트와 같이 반복 가능한(iterable)객체가 주어졌을 때 내부의 원소가 몇번씩 등장했는지 알려줌

from collections import Counter
#Counter객체로 만들어짐
counter = Counter(['red','blue','red','green','blue','blue'])

print(counter['blue'])
print(counter['green'])
print(dict(counter)) #사전 자료형으로 반환

 

6. 최대 공약수, 최소 공배수 : math

#최대 공약수, 최소 공배수 : math 
import math

# 최대 공약수 (GCD)계산
print(math.gcd(21, 14))

#최소 공배수(LCM)를 구하는 함수
def lcm(a,b):
  return a * b// math.gcd(a,b)

print(lcm(21,14))
728x90