Coding Test

코테에서 자주 쓰이는 Python 코드/패턴 모음

jimmmy_jin 2025. 6. 13. 21:53

📦 자주 쓰이는 Python 코드/패턴 모음

 

 

🔢 1. 

Counter

 – 등장 횟수 세기

from collections import Counter
count = Counter(nums)

 

  • 주로: 빈도 수 기반 정렬, top-k 문제
  • 예시: count.most_common(1) → 가장 많이 나온 항목

 


 

🔁 2. 

defaultdict

 – 키 초기화 없이 값 추가

from collections import defaultdict
d = defaultdict(int)
d[key] += 1

 

  • 주로: dict에 리스트, 숫자 누적할 때
  • 예: defaultdict(list) → 키마다 리스트 자동 생성

 


 

🥇 3. 

heapq

 – 최소/최대 힙

import heapq
heapq.heappush(heap, val)
heapq.heappop(heap)
heapq.nlargest(k, iterable, key=...)

 

  • 주로: 우선순위 큐, Top-K 문제, 최소거리 찾기 (다익스트라)

 


 

📚 4. 

zip

, 

enumerate

, 

map

for i, val in enumerate(arr):  # 인덱스 + 값
for a, b in zip(list1, list2):  # 두 리스트 묶기
list(map(int, input().split()))  # 빠른 입력 파싱

 

  • 주로: 배열 탐색, 위치 추적

 


 

💨 5. 

sorted

 + 

key

sorted(arr, key=lambda x: x[1], reverse=True)

 

  • 주로: 값 기준 정렬, 조건 기반 정렬

 


 

🧵 6. 

any()

 / 

all()

any(x > 0 for x in arr)  # 하나라도 True
all(x > 0 for x in arr)  # 전부 True

 

  • 주로: 조건 판별 간결하게 처리할 때

 


 

🔗 7. 

set

 – 중복 제거 및 교집합

set1 = set(arr)
set2 = set(arr2)
set1 & set2  # 교집합

 

  • 주로: 중복 제거, 두 집합 비교

 


 

⏱ 8. 슬라이딩 윈도우 / 투 포인터

left = 0
for right in range(len(arr)):
    while 조건 안 맞으면:
        left += 1
    # 현재 [left:right] 구간 처리

 

  • 주로: 연속 부분 배열, 최장 구간 찾기 문제

 


 

🧩 9. 이진 탐색 (

bisect

)

from bisect import bisect_left, bisect_right
i = bisect_left(arr, target)

 

  • 주로: 정렬된 배열에서 값의 위치 찾기 (O(log n))

 


 

📐 10. 그래프 – 

deque

(BFS) / DFS 재귀

from collections import deque

# BFS
q = deque([start])
while q:
    node = q.popleft()
    for next in graph[node]:
        q.append(next)

# DFS
def dfs(node):
    visited[node] = True
    for next in graph[node]:
        if not visited[next]:
            dfs(next)

 

  • 주로: 경로 찾기, 영역 개수 세기, 순환 판별 등

 


 

🔥 보너스: 트릭성 패턴

패턴설명

-heapq 최대 힙 구현 (heapq는 최소힙만 있음)
''.join(sorted(s)) 문자열 정렬 → 아나그램 판단
collections.deque 양쪽 삽입/삭제 O(1)
lambda + sorted() 특정 기준 정렬
enumerate() 인덱스 추적용

 


 

'Coding Test' 카테고리의 다른 글

8. Product of Array Except Self and Longest Consecutive Sequence  (0) 2025.06.16
6. Top K Frequent Elements  (0) 2025.06.13
5. Group Anagrams  (0) 2025.06.12
3. Valid Anagram  (0) 2025.06.11
2. Best Time to Buy and Sell Stock  (0) 2025.06.11