Post

파이썬 코테 꿀팁

파이썬 코테 벼락치기는 이거로 해결

파이썬 코테 꿀팁

입력

1
2
3
4
5
6
import sys

input = sys.stdin.readline

n = int(input()) # 한 개 정수 입력받기
n, m = map(int, input().split()) # 여러 개 정수 입력받기
  • 파이썬의 기본 input() 은 느리다. 위 방법으로 자주 사용한다.

재귀 깊이 제한 늘리기

1
2
import sys
sys.setrecursionlimit(10**6)
  • DFS 등과 같이 재귀를 사용하는 경우 재귀 제한을 늘려야 하는 경우가 있다.
  • 파이썬은 기본적으로 1000번 정도로 재귀를 제한하고 있기 때문

n차원 배열 생성 및 초기화 (list comprehension)

1
2
3
list = [[0] * m for _ in range(n)]

squares = [i * i for i in range(10)] # 0, 1, 4, 9, 16, ...

삼항 연산자

1
result = "합격" if score >= 60 else "불합격"

대괄호 무시하고 리스트 원소 출력하기

1
2
3
arr = [1, 2, 3]
print(arr) # [1, 2, 3]
print(*arr) # 1 2 3

순열, 조합 생성하기

1
2
3
4
5
6
7
8
9
from itertools import permutations, combinations

cards = ['A', 'B', 'C']

perm = list(permutations(cards, 2))
# [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

comb = list(combinations(cards, 2))
# [('A', 'B'), ('A', 'C'), ('B', 'C')]

리스크, 튜플 등을 특정 구분자로 합치기 (join)

1
2
3
4
5
my_list = ['apple', 'banana', 'orange']

result = ",".join(my_list)

print(result) # apple,banana,orange

딕셔너리 키 없을 때 기본값 자동 생성 (defaultdict)

1
2
3
4
5
6
7
from collections import defaultdict

graph = defaultdict(list)
graph['A'].append('B')

counts = defaultdict(int)
counts['apple'] += 1

리스트 원소 개수를 저장하는 방법 (Counter)

1
2
3
4
5
from collections import Counter

arr = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counts = Counter(arr)
# Counter({'apple': 3, 'banana': 2, 'orange': 1})

무한대 설정

1
2
import math
min_val = math.inf # 또는 float('inf')

우선순위 큐 (heapq)

1
2
3
4
5
6
7
8
import heapq

heap = []
heapq.heappush(heap, 4)
heapq.heappush(heap, 1)
heapq.heappush(heap, 7)

print(heapq.heappop(heap))
  • 다익스트라, MST 구현 시 사용한다.
  • 기본적으로 최소 힙이며, 최대 힙은 부호를 반전시켜 사용한다.

큐 (deque)

1
2
3
4
5
from collections import deque

queue = deque([1, 2, 3])
queue.append(4)
item = queue.popleft()

스택 (deque)

1
2
3
4
5
from collections import deque

stack = deque([1, 2, 3])
stack.append(4)
item = stack.pop()
  • deque 로 큐, 스택 모두 표현 가능하다.
  • deque 로 큐, 스택을 구현하는 경우 보통 원소 삽입 시 append 를 사용하지만, 원소 제거 시 큐는 popleft, 스택은 pop 을 사용한다.

이진 탐색 (bisect)

1
2
3
4
5
6
7
8
9
10
from bisect import bisect_left, bisect_right

arr = [1, 2, 4, 4, 8]

left_idx = bisect_left(arr, 4) # 2

right_idx = bisect_right(arr, 4) # 4

# 값이 4인 원소의 개수
count = right_idx - left_idx
  • C++에서 lower_boundbisect_left에, upper_boundbisect_right에 대응된다.

커스텀 정렬

1
list.sort(key=lambda x:(len(x),sum(x),x))

두 개 이상의 리스트를 같은 인덱스로 짝지어 순회 (zip)

1
2
for s, t in zip(schedules, timelogs):
    print(f"일정: {s}, 시간: {t}")
This post is licensed under CC BY 4.0 by the author.