[python] itertools 사용법(순열, 조합)

C__W.A·2022년 4월 19일
0

Python

목록 보기
6/6

알고리즘 문제를 풀다 보면 경우의 수를 따져야 되는 경우가 있다. 그럴 때 유용하게 사용할 수 있는 라이브러리가 itertools이다.

✅combinations(iterable, t)

✍iterable(반복 가능한 객체Iterable이란?)에서 원소 개수가 t개인 조합 뽑기

from itertools import combinations

a = "abcd"

for i in combinations(a, 2):
    print(i)

실행결과 :
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
('c', 'd')

✅combinations_with_replacement(iterable, t)

✍🏻iterable에서 원소 개수가 t개인 중복 조합 뽑기

from itertools import combinations_with_replacement

a = "abcd"

for i in combinations_with_replacement(a, 2):
    print(i)

실행결과 : 

('a', 'a')
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'b')
('b', 'c')
('b', 'd')
('c', 'c')
('c', 'd')
('d', 'd')

✅permutations(iterable, t)

✍🏻iterable에서 원소 개수가 t개인 순열 뽑기

t값을 통해서 최대길을 지정 가능, t= none으로 설정하면 최대길이 리턴


from itertools import permutations

a = "abc"

for i in permutations(a):
  print(i)
  
 실행결과 :
 ('a','b','c')
 ('a','c','b')
 ('b','a','c')
 ('b','c','a')
 ('c','a','b')
 ('c','b','a')

✅product(iterables, repeat=1)

✍🏻여러 iterable의 데카르트곱 리턴

product는 여러 iterable을 넣어줄 수도 있고 짝을 지어 리턴할 수 있습니다.

from itertools import product

e1 = ["a", "b"]
e2 = [1, 2]

for i in product(e1,e2, repeat=1)
	print(i)
    
실행결과
("A", 1)
("A", 2)
("B", 1)
("B", 2)

0개의 댓글