advent_of_code/2023/day1/python/main.py

45 lines
1016 B
Python
Raw Normal View History

import re
import copy
f = open('input.txt', 'r')
# content = f.read()
digits = [
['one', '1'],
['two', '2'],
['three', '3'],
['four', '4'],
['five', '5'],
['six', '6'],
['seven', '7'],
['eight', '8'],
['nine', '9'],]
sum = 0
while line := f.readline():
min_idx = len(line)
min_val = ''
max_idx = 0
max_val = ''
for digit in digits:
idx = line.find(digit[0])
if ((idx != -1) and (idx < min_idx)):
min_idx = copy.copy(idx)
min_val = digit[1]
line = line[:min_idx]+min_val+line[min_idx:]
for digit in digits:
idx = line.rfind(digit[0])
if idx > max_idx:
max_idx = copy.copy(idx)
max_val = digit[1]
line = line[:max_idx]+max_val+line[max_idx:]
# print(line.rstrip())
new_line = re.sub("[^0-9]", "", line.rstrip())
num = int(new_line[0])*10+int(new_line[-1])
# print(num)
sum = sum + num
f.close()
print(sum)