-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.py
92 lines (66 loc) · 1.87 KB
/
solver.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
import collections
import inspect
import math
import os
cwd = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
with open(os.path.join(cwd, "example.txt"), "r") as f:
lines = f.read().splitlines()
def get_neighbours(x, y, lst):
return [
n
for n in [
(x, y - 1),
(x, y + 1),
(x - 1, y),
(x - 1, y - 1),
(x - 1, y + 1),
(x + 1, y),
(x + 1, y - 1),
(x + 1, y + 1),
]
if n[0] >= 0 and n[1] >= 0 and n[0] < len(lst[0]) - 1 and n[1] < len(lst) - 1
]
# part 1
res = 0
for y, line in enumerate(lines):
x_e = None
num = ""
for x, char in enumerate(line):
if char.isdigit():
x_e = x
num += char
if x != len(line) - 1:
continue
if not num:
continue
n_1 = get_neighbours(x_e - (len(num) - 1), y, lines)
n_2 = get_neighbours(x_e, y, lines) if len(num) > 1 else []
for x_n, y_n in n_1 + n_2:
if lines[y_n][x_n] not in ".0123456789":
res += int(num)
break
x_e = None
num = ""
print(res)
# part 2
res = collections.defaultdict(list)
for y, line in enumerate(lines):
x_e = None
num = ""
for x, char in enumerate(line):
if char.isdigit():
x_e = x
num += char
if x != len(line) - 1:
continue
if not num:
continue
n_1 = get_neighbours(x_e - (len(num) - 1), y, lines)
n_2 = get_neighbours(x_e, y, lines) if len(num) > 1 else []
for x_n, y_n in n_1 + n_2:
if lines[y_n][x_n] == "*":
res[(x_n, y_n)].append(int(num))
break
x_e = None
num = ""
print(sum(math.prod(res) for res in res.values() if len(res) == 2))