0. 방향 벡터
# direction: 서, 남, 동, 북
dx = [0, 1, 0, -1]
dy = [-1, 0, 1, 0]
steps = [(0, -1), (1, 0), (0, 1), (-1, 0)]
steps = {'W': (0, -1), 'S': (1, 0), 'E': (0, 1), 'N': (-1, 0)}
1. itertools: 조합, 순열, 중복순열
import itertools
result = list(itertools.combinations([1, 2, 3], 2))
print(result) # [(1, 2), (1, 3), (2, 3)]
result = list(itertools.permutations([1, 2, 3], 2))
print(result) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
result = list(itertools.product([1, 2, 3], repeat=2))
print(result) # [(1, 1),(1, 2),(1, 3),(2, 1),(2, 2),(2, 3),(3, 1),(3, 2),(3, 3)]
2. collections: defaultdict, Counter
import collections
d = {}
d["apple"] = 0
d["apple"] += 1
print(d) # {'apple': 1}
d = collections.defaultdict(int) # 0으로 초기화
d["apple"] += 1
print(dict(d)) # {'apple': 1}
d = {}
d["x"] = []
d["x"].append(1)
print(d) # {'x': [1]}
d = collections.defaultdict(list) # [] 로 초기화
d["x"].append(1)
print(dict(d)) # {'x': [1]}
d = collections.Counter(["apple", "banana", "apple"])
print(dict(d)) # {'apple': 2, 'banana': 1}
3. functools: cmp_to_key
import functools
def comparator(x, y):
return 1 if str(x) > str(y) else -1
print(sorted([10, 4, 3, 2], key=lambda x: str(x))) # [10, 2, 3, 4]
print(sorted([10, 4, 3, 4], key=functools.cmp_to_key(comparator))) # [10, 2, 3, 4]
4. max()
a = ["a", "ab", "abc"]
print(max(a, key=len)) # abc
d = {"apple": 20, "banana": 10}
print(max(d)) # 키의 최대값 = banana
print(max(d.values())) # 값의 최대값 = 20
print(max(d, key=lambda x: d[x])) # 값이 최대인 키 = apple, max(d, key=d.get)
'알고리즘 이론' 카테고리의 다른 글
3-3. [그래프 탐색] 백트래킹 (0) | 2020.10.24 |
---|---|
3-2. [그래프 탐색] Kruskal, Prim (최소신장트리) (0) | 2020.10.03 |
3-1. [그래프 탐색] BFS (전체탐색) Dijkstra (최단거리) (0) | 2020.10.03 |
2-1. [정렬], [이분탐색] (0) | 2020.10.02 |
1-3. [구현] 수학 (0) | 2020.09.30 |