-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
351 lines (272 loc) · 7.55 KB
/
utils.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import operator
from collections import deque
from functools import reduce
from itertools import (
groupby,
)
import re
from typing import (
Callable,
Collection,
Iterable,
Iterator,
)
def load_input():
import json
import os.path
home = os.path.dirname(os.path.join(__file__))
session_path = os.path.join(home, 'session.json')
with open(session_path, 'r') as stream:
session_data = json.loads(stream.read())
token = session_data['session']
cwd = os.getcwd()
cwd, day = os.path.split(cwd)
day = day.lstrip('0')
cwd, year = os.path.split(cwd)
import urllib.request
import urllib.error
import shutil
opener = urllib.request.build_opener()
opener.addheaders = [
("Cookie", "session={}".format(token)),
("User-Agent", "python-requests/2.19.1"),
]
url = "https://adventofcode.com/{}/day/{}/input".format(year, day)
with opener.open(url) as r:
with open("data.txt", "wb") as f:
shutil.copyfileobj(r, f)
def chain(*funcs):
"""
f = chain(f1, f2, f3, f4)
is equivalent to
f = lambda arg: f4(f3(f2(f1(arg))))
"""
def chained(arg):
return reduce(lambda r, f: f(r), funcs, arg)
return chained
def matrix_next4(matrix, row, col):
for r, c in ((row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)):
if not 0 <= r < len(matrix):
continue
if not 0 <= c < len(matrix[row]):
continue
yield r, c
def matrix_next8(matrix, row, col):
for r, c in (
(row - 1, col - 1), (row, col - 1), (row + 1, col - 1),
(row - 1, col), (row + 1, col),
(row - 1, col + 1), (row, col + 1), (row + 1, col + 1),
):
if not 0 <= r < len(matrix):
continue
if not 0 <= c < len(matrix[row]):
continue
yield r, c
def matrix_drawline(matrix, a, b, value):
while a != b:
i, j = a
matrix[i][j] = value
a = cell_move_towards(a, b)
i, j = a
matrix[i][j] = value
def matrix_print(matrix, translation=None):
translation = translation or {}
def stringify(cell) -> str:
if cell in translation:
return str(translation[cell])
if isinstance(cell, float):
return f'{cell:.2}'
return str(cell)
stringified = [
[stringify(cell) for cell in row]
for row in matrix
]
max_len = max(
len(cell)
for row in stringified
for cell in row
)
for row in stringified:
for cell in row:
print(f'{cell:>{max_len}}', end=' ')
print()
def matrix_boundaries(matrix, func):
top = len(matrix) - 1
bottom = 0
left = len(matrix[0]) - 1
right = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if func(matrix[i][j]):
top = min(top, i)
bottom = max(bottom, i)
left = min(left, j)
right = max(right, j)
return top, bottom, left, right
def matrix_crop(matrix, top, bottom, left, right):
return [
row[left: right + 1]
for row in matrix[top: bottom + 1]
]
def bfs(*start):
visited = set()
queue = deque()
queue.extend(start)
step = 0
while queue:
for _ in range(len(queue)):
item = queue.popleft()
if item in visited:
continue
visited.add(item)
yield item, queue, step
step += 1
# NUMBERS
inf = float('inf')
def sign(x):
return 1 if x > 0 else -1 if x < 0 else 0
def int_from_bits(bits):
return int(''.join(map(chain(int, str), bits)), 2)
# STRINGS
def str_common(*strings: str) -> str:
"""
>>> str_common("abc", "abd", "cbe")
'b'
"""
return "".join(
reduce(
lambda x, y: x & y,
map(set, strings),
)
)
def str_group(s: str) -> list[str]:
"""
>>> list(str_group("aaabbbccc"))
['aaa', 'bbb', 'ccc']
"""
return [
''.join(group)
for _, group in groupby(s)
]
def str_integers(s: str) -> list[int]:
"""
>>> str_integers("12345")
[12345]
>>> str_integers("send 5 from 12345 to 67890")
[5, 12345, 67890]
>>> str_integers("send -5 from 12345 to 67890")
[-5, 12345, 67890]
"""
return lmap(int, re.findall(r'-{,1}\d+', s))
# LISTS
def iter_chunks(s: Collection, n: int) -> Iterator:
"""
>>> list(iter_chunks("123456789", 3))
['123', '456', '789']
>>> list(iter_chunks([1, 2, 3, 4, 5, 6, 7, 8, 9], 2))
[[1, 2], [3, 4], [5, 6], [7, 8]]
"""
for i in range(0, len(s) - n + 1, n):
yield s[i: i + n]
def iter_window(s: Collection, n: int) -> Iterator:
"""
>>> list(iter_window("123456789", 3))
['123', '234', '345', '456', '567', '678', '789']
>>> list(iter_window([1, 2, 3, 4, 5, 6, 7, 8, 9], 2))
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]
"""
for i in range(len(s) - n + 1):
yield s[i: i + n]
def is_subsequence(s: Iterable, t: Iterable) -> bool:
"""
>>> is_subsequence("abc", "ahbgdc")
True
>>> is_subsequence("axc", "ahbgdc")
False
"""
it = iter(t)
return all(c in it for c in s)
def list_startswith(items: list, prefix: list) -> bool:
"""
>>> list_startswith([1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3])
True
>>> list_startswith([1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4])
False
"""
return items[:len(prefix)] == prefix
def list_split(items: list, sep: list) -> list[list]:
"""
>>> list_split([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 5, 6])
[[1, 2, 3], [7, 8, 9]]
"""
result = []
current = []
i = 0
while i < len(items):
if list_startswith(items[i:], sep):
result.append(current)
current = []
i += len(sep)
else:
current.append(items[i])
i += 1
if current:
result.append(current)
return result
def lmap(func: Callable, sequence: Iterable) -> list:
"""
>>> lmap(int, "12345")
[1, 2, 3, 4, 5]
"""
return list(map(func, sequence))
def tmap(func: Callable, sequence: Iterable) -> tuple:
"""
>>> tmap(int, "12345")
(1, 2, 3, 4, 5)
"""
return tuple(map(func, sequence))
def mul(sequence: Iterable):
"""
>>> mul([1, 2, 3, 4, 5])
120
"""
return reduce(operator.mul, sequence, 1)
def first(sequence: Iterable):
return next(iter(sequence))
# CELLS
def cell_dist4(a, b) -> int:
dx, dy = abs(a[0] - b[0]), abs(a[1] - b[1])
return dx + dy
def cell_dist8(a, b) -> int:
dx, dy = abs(a[0] - b[0]), abs(a[1] - b[1])
return max(dx, dy)
def cell_move_towards(a, b):
dx, dy = b[0] - a[0], b[1] - a[1]
return a[0] + sign(dx), a[1] + sign(dy)
# VECTORS
def triangle_area(a: float, b: float, c: float) -> float:
s = (a + b + c) / 2
m = s * (s - a) * (s - b) * (s - c)
return abs(m) ** 0.5
def vect_length(p1, p2) -> float:
x1, y1 = p1
x2, y2 = p2
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
# DICTIONARIES
def dict_swap(mapping: dict) -> dict:
"""
>>> dict_swap({"a": 1, "b": 2, "c": 3})
{1: 'a', 2: 'b', 3: 'c'}
"""
return {v: k for k, v in mapping.items()}
def dict_invert(mapping: dict) -> dict:
"""
>>> dict_invert({"a": 1, "b": 2, "c": 3})
{1: ['a'], 2: ['b'], 3: ['c']}
>>> dict_invert({"a": 1, "b": 2, "c": 1})
{1: ['a', 'c'], 2: ['b']}
"""
result = {}
for k, v in mapping.items():
result.setdefault(v, []).append(k)
return result