You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

53 lines
1.5 KiB

lines = open("input.txt", 'r').read().splitlines()
sum = 0
sum2 = 0
nonqual = ['0','1','2','3','4','5','6','7','8','9','.']
gears = {}
def checkValid(x,y):
if lines[x][y] == "*":
coord = str(x) + "," + str(y)
if coord not in gears:
gears[coord] = [int(num)]
else:
gears[coord].append(int(num))
return True
if lines[x][y] not in nonqual:
return True
for i in range(len(lines)):
columns = len(lines[i])
j = 0
while j < columns:
if lines[i][j].isnumeric():
num = ""
valid = False
for k in range(len(lines[i])):
if j+k >= columns:
break
if lines[i][j+k].isnumeric():
num += lines[i][j+k]
else:
break
lennum = len(num)
for x in range(0 if j == 0 else j-1, columns if j + lennum == columns else j+lennum+1):
if i != 0 and checkValid(i-1, x):
valid = True
if i != len(lines)-1 and checkValid(i+1, x):
valid = True
if j != 0 and checkValid(i, j-1):
valid = True
if j+lennum != columns and checkValid(i, j+lennum):
valid = True
if valid:
sum += int(num)
j += lennum
j += 1
for coord in gears:
if len(gears[coord]) == 2:
sum2 += gears[coord][0] * gears[coord][1]
print(sum)
print(sum2)