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 등과 같이 재귀를 사용하는 경우 제한을 늘려야 하는 경우가 있다.

n차원 배열 초기화

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

list comprehension

1
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
from itertools import permutations, combinations

permutations(iterable, r)
combinations(iterable, r)

리스크, 튜플 등을 특정 구분자로 합치기 - 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
8
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)     # O(1)
item = queue.popleft()
  • BFS, 위상 정렬 등에서 큐 역할

이진 탐색 - bisect

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

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

# 값이 4인 원소가 처음 나타나는 인덱스
left_idx = bisect_left(arr, 4)  # 2

# 값이 4인 원소가 들어갈 오른쪽 인덱스
right_idx = bisect_right(arr, 4) # 4

# 값이 4인 원소의 개수
count = right_idx - left_idx # 2

커스텀 정렬

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}")

입력

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 등과 같이 재귀를 사용하는 경우 제한을 늘려야 하는 경우가 있다.

n차원 배열 초기화

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

list comprehension

1
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
from itertools import permutations, combinations

permutations(iterable, r)
combinations(iterable, r)

리스크, 튜플 등을 특정 구분자로 합치기 - 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
8
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)) # 가장 작은 원소인 1이 출력됨
  • 다익스트라, MST 시 사용한다.
  • 기본적으로 최소 힙이며, 최대 힙은 부호를 반전시켜 사용한다.

큐 - deque

1
2
3
4
5
from collections import deque

queue = deque([1, 2, 3])
queue.append(4)     # O(1)
item = queue.popleft()
  • BFS, 위상 정렬 등에서 큐 역할

이진 탐색 - bisect

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

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

# 값이 4인 원소가 처음 나타나는 인덱스
left_idx = bisect_left(arr, 4)  # 2

# 값이 4인 원소가 들어갈 오른쪽 인덱스
right_idx = bisect_right(arr, 4) # 4

# 값이 4인 원소의 개수
count = right_idx - left_idx # 2

커스텀 정렬

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.