75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
|
#!/bin/python3
|
||
|
|
||
|
import re
|
||
|
import sys
|
||
|
from pprint import pprint
|
||
|
input_f = sys.argv[1]
|
||
|
count = 0
|
||
|
arr = []
|
||
|
|
||
|
with open(input_f) as file:
|
||
|
for line in file:
|
||
|
arr.append(list(line.lstrip().rstrip()))
|
||
|
|
||
|
X=len(arr[0])
|
||
|
Y=len(arr)
|
||
|
neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
|
||
|
for y2 in range(y-1, y+2)
|
||
|
if (-1 < x <= X and
|
||
|
-1 < y <= Y and
|
||
|
(x != x2 or y != y2) and
|
||
|
(0 <= x2 < X) and
|
||
|
(0 <= y2 < Y))]
|
||
|
checked = []
|
||
|
numbers = []
|
||
|
|
||
|
def find_num(n,m,result):
|
||
|
gear_numbers = []
|
||
|
tmp_numbers = []
|
||
|
gear_count = 0
|
||
|
for i in n:
|
||
|
if arr[i[0]][i[1]].isdigit() and i not in checked:
|
||
|
ctmp = 1
|
||
|
left=False
|
||
|
right=False
|
||
|
num = str(arr[i[0]][i[1]])
|
||
|
checked.append(i)
|
||
|
while left == False or right == False:
|
||
|
while arr[i[0]][i[1]-ctmp].isdigit() and (i[0],i[1]-ctmp) not in checked:
|
||
|
checked.append((i[0],i[1]-ctmp))
|
||
|
num = str(arr[i[0]][i[1]-ctmp]) + num
|
||
|
ctmp = ctmp + 1
|
||
|
left = True
|
||
|
ctmp = 1
|
||
|
while i[1]+ctmp < len(arr) and arr[i[0]][i[1]+ctmp].isdigit() and (i[0],i[1]+ctmp) not in checked:
|
||
|
checked.append((i[0],i[1]+ctmp))
|
||
|
num = num + str(arr[i[0]][i[1]+ctmp])
|
||
|
ctmp = ctmp + 1
|
||
|
right = True
|
||
|
gear_count += 1
|
||
|
numbers.append(int(num))
|
||
|
tmp_numbers.append(int(num))
|
||
|
if gear_count == 2:
|
||
|
for i in range(0,gear_count):
|
||
|
gear_numbers.append(numbers[len(numbers)-i-1])
|
||
|
if len(gear_numbers) == 2:
|
||
|
#print("gears ",end="")
|
||
|
#print(arr[m[0]][m[1]],end="")
|
||
|
#print(" ",end="")
|
||
|
#print(gear_numbers)
|
||
|
return result + (gear_numbers[0]*gear_numbers[1])
|
||
|
return result
|
||
|
|
||
|
sym = ()
|
||
|
result = 0
|
||
|
for idx,i in enumerate(arr):
|
||
|
for jdx,j in enumerate(i):
|
||
|
tmp = arr[idx][jdx]
|
||
|
if tmp.isdigit() == False and tmp != '.':
|
||
|
#print(tmp + " (" + str(idx) + "," + str(jdx) + ")")
|
||
|
n = neighbors(idx,jdx)
|
||
|
sym = (idx,jdx)
|
||
|
result = find_num(n,sym,result)
|
||
|
|
||
|
print(result)
|