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.
 
 

64 lines
1.8 KiB

#!/usr/bin/env python3
import sys
NUMS = ['0','1','2','3','4','5','6','7','8','9']
def get_number(schema, x, y):
start = x
while start > 0:
if schema[y][start-1] in NUMS: start -= 1
else: break
num = ''
while start < len(schema[y]) and schema[y][start] in NUMS:
num += schema[y][start]
start += 1
return int(num), start
def part_number(schema, x, y):
for i in [max(0,x-1), x, min(x+1, len(schema[x])-1)]:
for j in [max(0,y-1), y, min(y+1, len(schema)-1)]:
if not (schema[j][i] in NUMS or schema[j][i] == '.'):
return get_number(schema, x, y)
return 0, x+1
def gear_ratio(schema, x, y):
parts = [0,0]
for j in [max(0,y-1), y, min(y+1, len(schema)-1)]:
next_x = 0
for i in [max(0,x-1), x, min(x+1, len(schema[x])-1)]:
if i < next_x: continue
if schema[j][i] in NUMS:
if parts[0] == 0: parts[0], next_x = get_number(schema, i, j)
else: parts[1], next_x = get_number(schema, i, j)
return parts[0] * parts[1]
if __name__ == '__main__':
schema = [list(line.strip('\n')) for line in open(sys.argv[1])]
# challenge 1
res1 = 0
for y, line in enumerate(schema):
next_x = 0
for x, sym in enumerate(line):
if x < next_x: continue
if sym in NUMS:
n, next_x = get_number(schema, x, y)
res1 += n
else: continue
res1 = str(res1)
print(f"challenge 1:\n{res1}\n")
# challenge 2
res2 = 0
for y, line in enumerate(schema):
for x, sym in enumerate(line):
if sym == '*': res2 += gear_ratio(schema, x, y)
else: continue
res2 = str(res2)
print(f"challenge 2:\n{res2}\n")