IT : 기초라는 뿌리

순열과 조합 기초 본문

코딩테스트

순열과 조합 기초

Parkej 2021. 8. 6. 19:51
언어 : 파이썬
라이브러리 사용 : O

 

순열 : 순서가 있는 열
조합 : 순서가 없는 것

순열 (순서가 중요하다)
 - 1, 2, 3
 - 2, 1, 3
 원소는 같지만 순서가 다르다

조합 (순서만 다르지 원소는 같다)
 - 1, 2, 3
 - 2, 1, 3
  같은 것이라 생각한다. 

 

 

순열 
 - permutations : 중복 없는 순열
 - product : 중복 있는 순열

 

from itertools import permutations # 중복 미포함
from itertools import product # 중복 포함

a = [1,2,3]

# 문법 틀
# permutations(반복 가능 객체, r)
# product(반복 가능 객체, repeat=2)

# print(list(permutations(a,2))) # 중복 없는 순열 => 요소 2개 뽑기
# print(list(product(a,'abc'))) # 중복 있는 순열 => a,b,c 문자를 포함한 순열

for i in product(a,repeat=3):
  print(i)
print('-'*20)

for i in permutations(a,3):
  print(i)
print('-'*20)

 


실행결과
product

 

permutations

조합
 - combinations : 중복 없는 조합 
 - combinations_with_replacement : 중복 있는 조합

 

from itertools import combinations
from itertools import combinations_with_replacement as comr

a = [1,2,3]

# 문법 틀
# combinations(반복 가능 객체, r)
# combinations_with_replacement(반복 가능 객체, r

# print(list(combinations(a,2))) # 중복 없는 조합
# print(list(comr(a,2))) # 중복 있는 조합

# for i in comr(a,2):
#   print(i)

 


실행결과
위 combinations, 아래 combinations_with_replacement

 

 

 

 

* 나중에 문제풀이하기 and 라이브러리 안쓰고 직접 구현해보기