1. math
import math
print(math.factorial(5)) # 5! = 120
print(math.gcd(36, 60)) # 최대공약수(GCD) = 12
print(math.sqrt(25)) # 제곱근 = 5.0
print(math.ceil(3.1)) # 올림 = 4
print(math.floor(3.9)) # 내림 = 3
2. itertools
import itertools
arr = [1, 2, 3]
# 순열 (3개 중 2개를 선택하는 모든 경우) -> 순서 의미 있음
print(list(itertools.permutations(arr, 2)))
#[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
# 조합 (3개 중 2개를 뽑는 경우) -> 순서 의미 없음
print(list(itertools.combinations(arr, 2)))
#[(1, 2), (1, 3), (2, 3)]
# 중복 조합
print(list(itertools.combinations_with_replacement(arr, 2)))
# [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
3. collections
deque
from collections import deque
dq = deque([1, 2, 3])
dq.append(4) # 오른쪽 추가
dq.appendleft(0) # 왼쪽 추가
print(dq) # deque([0, 1, 2, 3, 4])
dq.pop() # 오른쪽 제거
dq.pop(left) # 왼쪽 제거
print(dq) # deque([1, 2, 3])
Counter
from collections import Counter
arr = ['a', 'b', 'c', 'a', 'b', 'a']
counter = Counter(arr)
print(counter) # Counter({'a': 3, 'b': 2, 'c': 1})
print(counter['a']) # 3
print(counter.most_common(1)) # [('a', 3)]
4. heapq
최소 힙(기본)
import heapq
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 4)
print(heapq.heappop(heap)) # 1
print(heapq.heappop(heap)) # 3
최대 힙
heap = []
heapq.heappush(heap, -3)
heapq.heappush(heap, -1)
heapq.heappush(heap, -4)
print(-heapq.heappop(heap)) # 4
print(-heapq.heappop(heap)) # 3
5. bisect (이진탐색)
import bisect
arr = [1, 2, 4, 4, 5, 6]
print(bisect.bisect_left(arr, 4)) # 2 (4가 처음 등장하는 인덱스)
print(bisect.bisect_right(arr, 4)) # 4 (4가 끝나는 위치)
# 값 삽입
bisect.insort(arr, 3)
print(arr) # [1, 2, 3, 4, 5, 5, 6]
6. functools
lru_cach(메모이제이션)
from functools import lru_cache
@lru_cache(None)
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print(fib(50))
728x90
'공부 > 알고리즘' 카테고리의 다른 글
2D 누적 합(Prefix Sum) 기법 (0) | 2025.03.21 |
---|---|
배낭 문제(Knapsack Problem) (0) | 2025.02.28 |
알고리즘 접근 방법 (0) | 2025.02.24 |
다익스트라(Dijkstra) - Python, heapq (0) | 2025.02.07 |
유니온 파인드(Union-Find) - Python (0) | 2024.12.10 |