반응형
*** 지속적으로 추가 예정 ***
수행 시간 측정
import time
start_time = time.time()
"""
#
#
"""
end_time = time.time()
print(f"total time: {end_time - start_time}")
좌표 상하좌우 이동
r = 4
c = 6
mat = [[0] * c for _ in range(r)]
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
x, y = 0 # 기존 좌표
nx, ny = x + dx, y + dy # 다음 좌표
if 0 <= nx < c and 0 <= ny < r: # 다음 좌표가 범위 내
"""
#
#
#
"""
특정 키 기준으로 정렬 with 람다 표현식
arr = [('abc', 5), ('def', 2), ('ghi', 8)]
def my_key(x):
return x[1]
print(sorted(arr, key=my_key))
print(sorted(arr, key=lambda x: x[1]))
순열과 조합
from itertools import permutations as perm
from itertools import combinations as comb
from itertools import product
from itertools import combinations_with_replacement as comb_re
data = ['A', 'B', 'C']
# 순열
result = list(perm(data, 3)) # nP3
print(result)
# 조합
result = list(comb(data, 2)) # nC2
print(result)
# 중복 순열
result = list(product(data, repeat=2)) # 중복을 허용하여 2개 순열
print(result)
# 중복 조합
result = list(comb_re(data, 2)) # 중복을 허용하여 2개 조합
print(result)
원소 개수 세기
from collections import Counter
counter = Counter([1, 2, 2, 3, 4, 5, 5, 5])
print(counter[1])
print(counter[5])
최대 공약수, 최소 공배수
import math
# 최소 공배수 [LCM]
def lcm(a, b):
return a * b // math.gcd(a,b)
print(math.gcd(21, 14)) # 최대 공약수 [GCD]
print(lcm(21, 14)) # 최소 공배수 [LCM]
힙 정렬
import heapq
# 오름차순 정렬
def heapsort(iter):
h = []
result = []
for v in iter:
heapq.heappush(h, v)
for i in range(len(h)):
result.append(heapq.heappop(h))
return result
파이썬에서는 기본적으로 Min Heap만 제공하므로, push와 pop에서 부호를 바꿈으로 Max Heap처럼 구현할 수 있다.
import heapq
# 내림차순 정렬
def heapsort(iter):
h = []
result = []
for v in iter:
heapq.heappush(h, -v)
for i in range(len(h)):
result.append(-heapq.heappop(h))
return result
재귀 깊이 제한 변경
import sys
sys.setrecursionlimit(10**6)
반응형