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.

44 lines
1.5 KiB

lines = [x.strip("\n") for x in open('inputs/day1.txt').readlines()]
digit_names = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
def digits(lines: list[str]) -> list[int]:
dgts = []
for line in lines:
numbers = ''
for char in line:
if char.isdigit():
numbers += char
break
for char in line[::-1]:
if char.isdigit():
numbers += char
break
dgts.append(int(numbers))
return dgts
def transform_digits(lines: list[str]) -> list[str]:
newlines = []
for line in lines:
indices = {}
for idx, c in enumerate(digit_names):
c_loc = [i for i in range(len(line)) if line.startswith(c, i)]
while c_loc:
loc = c_loc.pop(0)
indices[loc] = str(idx+1)
if len(indices) == 0:
newlines.append(line)
else:
first_index = sorted(indices)[0]
first_number = int(indices[first_index])
second_index = sorted(indices)[-1]
second_number = int(indices[second_index])
newline = line[:first_index+1] + str(first_number) + line[first_index+1:]
newline = newline[:second_index+2] + str(second_number) + newline[second_index+2:]
newlines.append(newline)
return newlines
print(f'Part 1 Solution = {sum(digits(lines))}')
print(f'Part 2 Solution = {sum(digits(transform_digits(lines)))}')