본문 바로가기

코테 문제

파이썬 itertools사용법

 알고리즘 문제를 풀다보면, 순열.조합을 사용해야할때가 있다.

 

itertools라이브러리를 이용하는 방법을 공부하자. 

 

대표적인 조합형 이터레이터 함수

 

- combinations

- combinations_with_replacement()

- product()

- permutations()


  • combinations(list, r) : list에서 원소 개수가 r개인 조합 뽑기
1111
from itertools import combinations

number = [-2, 3, 0, 2, -5]

for ii in combinations(number, 2):
    print(ii)
    
 #(-2, 3) 
 #(-2, 0) 
 #(-2, 2) 
 #(-2, -5) 
 #(3, 0) 
 #(3, 2) 
 #(3, -5) 
 #(0, 2) 
 #(0, -5) 
 #(2, -5)

 


  • - combinations_with_replacement(list, r) : list에서 원소개수가 r개인 중복조합 뽑기

 

from itertools import combinations_with_replacement

number = [-2, 3, 0, 2, -5]

for ii in combinations_with_replacement(number, 3):
    print(ii)
'''(-2, -2, -2)
(-2, -2, 3)
(-2, -2, 0)
(-2, -2, 2)
(-2, -2, -5)
(-2, 3, 3)
(-2, 3, 0)
(-2, 3, 2)
(-2, 3, -5)
(-2, 0, 0)
(-2, 0, 2)
(-2, 0, -5)
(-2, 2, 2)
(-2, 2, -5)
(-2, -5, -5)
(3, 3, 3)
(3, 3, 0)
(3, 3, 2)
(3, 3, -5)
(3, 0, 0)
(3, 0, 2)
(3, 0, -5)
(3, 2, 2)
(3, 2, -5)
(3, -5, -5)
(0, 0, 0)
(0, 0, 2)
(0, 0, -5)
(0, 2, 2)
(0, 2, -5)
(0, -5, -5)
(2, 2, 2)
(2, 2, -5)
(2, -5, -5)
(-5, -5, -5)'''

 

  • - permutations(list, r=None) : list에서 원소개수가 r개인 순열뽑기

      - r default : 최대 길이의 순열 리턴

from itertools import permutations

number = [-2, 3, 0]

for ii in permutations(number):
    print(ii)
'''(-2, 3, 0)
(-2, 0, 3)
(3, -2, 0)
(3, 0, -2)
(0, -2, 3)
(0, 3, -2)'''

  • product(list, repeat = 1) : 여러 list의 데카르트곱 리턴

product는 다른 함수와 달리 인자로 여러 iterable을 넣어줄 수 있고 그것들간의 모든 짝을 지어서 리턴합니다.

from itertools import product

num1 = [-1,-2,-3]
num2 = [1,2,3]
for ii in product(num1, num2, repeat = 1):
    print(ii)
## num1과 num2가 repeat번 반복해서 쌍을 짓는다.
'''(-1, 1)
(-1, 2)
(-1, 3)
(-2, 1)
(-2, 2)
(-2, 3)
(-3, 1)
(-3, 2)
(-3, 3)'''

##repeat을 2로 해보자
from itertools import product

num1 = [-1,-2]
num2 = [1,2]
for ii in product(num1, num2, repeat = 2):
    print(ii)
'''(-1, 1, -1, 1)
(-1, 1, -1, 2)
(-1, 1, -2, 1)
(-1, 1, -2, 2)
(-1, 2, -1, 1)
(-1, 2, -1, 2)
(-1, 2, -2, 1)
(-1, 2, -2, 2)
(-2, 1, -1, 1)
(-2, 1, -1, 2)
(-2, 1, -2, 1)
(-2, 1, -2, 2)
(-2, 2, -1, 1)
(-2, 2, -1, 2)
(-2, 2, -2, 1)
(-2, 2, -2, 2)'''

for ii in product(num1, num2,num1, num2, repeat =1):
    print(ii)
 ###위와 똑같은 값 리턴!!!

 

 

 

 

 

 

'코테 문제' 카테고리의 다른 글

코딩테스트1.  (0) 2023.02.17