-
Notifications
You must be signed in to change notification settings - Fork 2
/
snippets.py
74 lines (58 loc) · 1.74 KB
/
snippets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Stuff that I might want to copy out and reuse
import operator
OPS = {
x.__doc__.split()[3]: x
for k in dir(operator)
if not k.startswith('__')
and (x := getattr(operator, k)).__doc__.startswith("Same as a ")
}
def draw(painted):
minx = min(x for x, y in painted)
miny = min(y for x, y in painted)
maxx = max(x for x, y in painted)
maxy = max(y for x, y in painted)
l = ""
# XXX: add reversed if needed
for y in list((range(miny, maxy+1))):
for x in range(minx, maxx+1):
l += painted.get((x,y), ".")
l += "\n"
print(l)
import heapq
# This is A* if you pass a heuristic and a target, otherwise Dijkstra's
def dijkstra(m, edges, start, heuristic=None, target=None):
cost = {start: 0}
path = {}
todo = [(0, 0, start)]
explored = 0
while todo and todo[0][-1] != target:
_, k, cur = heapq.heappop(todo)
if k != cost[cur]:
continue
explored += 1
nbrs = list(edges(m, cur))
for nbr, weight in nbrs:
ncost = cost[cur] + weight
if nbr not in cost or ncost < cost[nbr]:
cost[nbr] = ncost
path[nbr] = cur
hcost = ncost if not heuristic else ncost + heuristic(nbr)
heapq.heappush(todo, (hcost, ncost, nbr))
return cost, path
def binary_search(pred, lo, hi=None):
"""Finds the first n in [lo, hi) such that pred(n) holds.
hi == None -> infty
"""
assert not pred(lo)
if hi is None:
hi = max(lo, 1)
while not pred(hi):
hi *= 2
assert pred(hi)
while lo < hi:
mid = (lo + hi) // 2
if pred(mid):
hi = mid
else:
lo = mid + 1
return lo