itertools & collections 정리from itertools (조합, 순열, 반복 패턴)permutations - 순열 (순서 중요)from itertools import permutations
arr = [1, 2, 3]
print(list(permutations(arr, 2))) # [(1,2), (1,3), (2,1), (2,3), (3,1), (3,2)]
r인 모든 순열 생성(1,2)와 (2,1)은 다름combinations - 조합 (순서 상관없음)from itertools import combinations
arr = [1, 2, 3]
print(list(combinations(arr, 2))) # [(1,2), (1,3), (2,3)]
r인 모든 조합 생성(1,2)와 (2,1)은 같음 (중복 제거)product - 중복 순열 (Cartesian Product)from itertools import product
arr = [1, 2, 3]
print(list(product(arr, repeat=2))) # [(1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3)]
combinations_with_replacement - 중복 조합from itertools import combinations_with_replacement
arr = [1, 2, 3]
print(list(combinations_with_replacement(arr, 2))) # [(1,1), (1,2), (1,3), (2,2), (2,3), (3,3)]
accumulate - 누적 합from itertools import accumulate
arr = [1, 2, 3, 4]
print(list(accumulate(arr))) # [1, 3, 6, 10] (prefix sum)
from collections (자료구조)Counter - 빈도수 세기from collections import Counter
arr = ['a', 'b', 'a', 'c', 'b', 'a']
counter = Counter(arr)
print(counter) # Counter({'a': 3, 'b': 2, 'c': 1})
print(counter['a']) # 3
most_common(n): 가장 많이 나온 n개 찾기defaultdict - 기본값 자동 할당from collections import defaultdict
d = defaultdict(int)
d['a'] += 1 # KeyError 없이 자동 초기화됨
print(d) # defaultdict(<class 'int'>, {'a': 1})
int, list, set 등 가능)deque - 빠른 큐/덱 연산from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0) # 왼쪽 삽입
dq.append(4) # 오른쪽 삽입
dq.popleft() # 왼쪽 삭제
dq.pop() # 오른쪽 삭제
print(dq) # deque([1, 2, 3])
OrderedDict - 순서 유지 딕셔너리from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
print(d) # OrderedDict([('a', 1), ('b', 2)])
dict도 순서 유지하긴 하지만, OrderedDict는 더 명확함namedtuple - 가독성 좋은 튜플from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y) # 1 2
| 모듈 | 기능 | 사용 예시 |
|---|---|---|
itertools.permutations | 순열 | list(permutations(arr, r)) |
itertools.combinations | 조합 | list(combinations(arr, r)) |
itertools.product | 중복 순열 | list(product(arr, repeat=r)) |
itertools.combinations_with_replacement | 중복 조합 | list(combinations_with_replacement(arr, r)) |
itertools.accumulate | 누적 합 | list(accumulate(arr)) |
collections.Counter | 빈도수 세기 | Counter(arr)['a'] |
collections.defaultdict | 기본값 딕셔너리 | d = defaultdict(int) |
collections.deque | 빠른 큐/덱 | dq.appendleft(x), dq.popleft() |
collections.OrderedDict | 순서 유지 딕셔너리 | OrderedDict() |
collections.namedtuple | 가독성 좋은 튜플 | Point = namedtuple('Point', ['x', 'y']) |
코딩테스트에서는 보통 Counter, defaultdict, deque, permutations, combinations 정도가 제일 많이 쓰임! 🚀