Day 3
This commit is contained in:
1 parent
5c5690a4a3
commit
0c3db95461
5 files changed
+417
No files matched your search
Executable
+63
@@ -0,0 +1,63 @@
|
||||
#!/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 = part_number(schema, x, y)
|
||||
res1 += n
|
||||
|
||||
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)
|
||||
res2 = str(res2)
|
||||
print(f"challenge 2:\n{res2}\n")
|
||||
|
||||
Reference in new issue
Block a user