advent-of-code-2023/day-1/part-2/part-2.py
2023-12-06 08:46:47 -06:00

60 lines
2 KiB
Python
Executable file

#!/usr/bin/env python3
DEBUG = False
num_text = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
#num_text = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}
with open('day-1/input', 'rt') as f:
numbers = []
for line in f:
# just removes the newline to make printing work a bit better
line = line.rstrip()
digit1 = -1
# go through each line, start at the beginning, and keep going until it either matches a digit or it spelled out
# can probably be made more efficient
for i in range(0, len(line)):
if line[i].isdigit():
digit1 = int(line[i])
else:
# spelled out detection
for num in num_text:
# to make sure it doesn't go over the end
# fancy if thing needed so it doesn't go way over the end
end = i + len(num) if i + len(num) < len(line) else len(line)
if line[i:end] in num_text:
digit1 = num_text.index(line[i:end])
if digit1 != -1:
break
if digit1 != -1:
break
if DEBUG:
print('digit 1 debug:', line, digit1)
# TODO: digit 2, basically the same thing in reverse
digit2 = -1
'''
for char in line:
if str.isdigit(char):
digit1 = char
break
for i in range(len(line) - 2, -1, -1):
if str.isdigit(line[i]):
digit2 = line[i]
break
'''
# append if nums found, otherwise print error
numbers.append(int(str(digit1) + str(digit2))) if digit1 != -1 and digit2 != -1 else print(line, 'failed:', digit1, digit2, end='\n\n')
total = 0
for num in numbers:
total += num
print(total)