import 하는것들

Leejaegun·2025년 3월 17일

코딩테스트 시리즈

목록 보기
18/49

코딩테스트에서 자주 쓰는 itertools & collections 정리

from itertools (조합, 순열, 반복 패턴)

1. 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)은 다름

2. 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)은 같음 (중복 제거)

3. 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)]
  • 중복 허용 순열 (모든 경우의 수)

4. 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)]
  • 중복 허용 조합 (조합인데 같은 원소 선택 가능)

5. accumulate - 누적 합

from itertools import accumulate

arr = [1, 2, 3, 4]
print(list(accumulate(arr)))  # [1, 3, 6, 10] (prefix sum)
  • 누적 합(Prefix Sum) 쉽게 구하기

from collections (자료구조)

1. 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개 찾기

2. defaultdict - 기본값 자동 할당

from collections import defaultdict

d = defaultdict(int)
d['a'] += 1  # KeyError 없이 자동 초기화됨
print(d)  # defaultdict(<class 'int'>, {'a': 1})
  • 존재하지 않는 키에도 기본값 할당 (int, list, set 등 가능)

3. 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])
  • O(1) 시간에 양쪽에서 추가/삭제 가능 → 큐 구현할 때 유용

4. OrderedDict - 순서 유지 딕셔너리

from collections import OrderedDict

d = OrderedDict()
d['a'] = 1
d['b'] = 2
print(d)  # OrderedDict([('a', 1), ('b', 2)])
  • 파이썬 3.6 이후부터 기본 dict도 순서 유지하긴 하지만, OrderedDict는 더 명확함

5. 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 정도가 제일 많이 쓰임! 🚀

profile
Lee_AA

0개의 댓글