43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import sys
|
|
|
|
input_file = sys.argv[1]
|
|
|
|
with open(input_file) as fd:
|
|
lines = [line.rstrip() for line in fd.readlines()]
|
|
|
|
height = len(lines)
|
|
width = len(lines[0])
|
|
|
|
gears = dict()
|
|
|
|
sum = 0
|
|
for i in range(height):
|
|
line = lines[i]
|
|
pn_str = ""
|
|
for j in range(width):
|
|
c = line[j]
|
|
# print(19, c)
|
|
if c.isnumeric():
|
|
if not pn_str:
|
|
left = j
|
|
pn_str += c
|
|
# print(20, c, pn_str)
|
|
if pn_str and (j == width - 1 or not line[j + 1].isnumeric()):
|
|
for ii in range(max(i - 1, 0), min(i + 1, height - 1) + 1):
|
|
for jj in range(max(left - 1, 0), min(j + 1, width - 1) + 1):
|
|
cc = lines[ii][jj]
|
|
# print(ii, jj, cc)
|
|
if cc == "*":
|
|
gears.setdefault((ii, jj), list())
|
|
gears[(ii, jj)].append(int(pn_str))
|
|
pn_str = ""
|
|
for gear_numbers in gears.values():
|
|
if len(gear_numbers) != 2:
|
|
continue
|
|
gear_ratio = gear_numbers[0] * gear_numbers[1]
|
|
sum += gear_ratio
|
|
|
|
print(sum)
|