-
Notifications
You must be signed in to change notification settings - Fork 17
/
day03.py
executable file
·77 lines (55 loc) · 1.65 KB
/
day03.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
#!/usr/bin/env python3
import sys
from math import prod
from collections import defaultdict
def adjacent_symbols(grid, r, start_c, height, width):
row = grid[r]
above = grid[r - 1] if r > 0 else []
below = grid[r + 1] if r < height - 1 else []
gears = []
adj_to_symbol = False
for c in range(max(0, start_c - 1), width):
if above and above[c] not in '0123456789.':
adj_to_symbol = True
if above[c] == '*':
gears.append((r - 1, c))
if below and below[c] not in '0123456789.':
adj_to_symbol = True
if below[c] == '*':
gears.append((r + 1, c))
if not row[c].isdigit():
adj_to_symbol |= row[c] != '.'
if row[c] == '*':
gears.append((r, c))
if c > start_c:
break
return adj_to_symbol, gears
def extract_number(row, start, length):
end = start + 1
while end < length and row[end].isdigit():
end += 1
return int(row[start:end])
# Open the first argument as input or use stdin if no arguments were given
fin = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
grid = list(map(str.rstrip, fin.readlines()))
height, width = len(grid), len(grid[0])
answer1 = answer2 = 0
gears = defaultdict(list)
for r, row in enumerate(grid):
c = 0
while c < width:
while c < width and not row[c].isdigit():
c += 1
if c >= width:
break
adj_to_symbol, adj_gears = adjacent_symbols(grid, r, c, height, width)
if adj_to_symbol:
number = extract_number(row, c, width)
answer1 += number
for rc in adj_gears:
gears[rc].append(number)
while c < width and row[c].isdigit():
c += 1
print('Part 1:', answer1)
answer2 = sum(map(prod, filter(lambda x: len(x) == 2, gears.values())))
print('Part 2:', answer2)