1
0
AOC_2023/Day-1/Part 2/solution.py

40 lines
1.0 KiB
Python

spelled_out_digits = [
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
]
def findFirstDigitInString(string: str) -> str:
lenght_of_string = len(string)
i = 0
while i < lenght_of_string:
substring = string[i:i+5]
if(string[i].isdigit()):
return string[i]
if (string[i].isalpha() ):
digit = [x for x in spelled_out_digits if substring.find(x) == 0 or substring.find(x[::-1]) == 0]
if len(digit) != 0:
return str(spelled_out_digits.index(digit[0]) + 1)
i+=1
numbers = []
with open("input.txt") as file:
line = file.readline()
while line :
firstdigit = findFirstDigitInString(line)
lastdigit = findFirstDigitInString(line[::-1])
numbers.append(int(f"{firstdigit}{lastdigit}"))
line = file.readline()
sum = 0
for n in numbers:
sum += n
print(f"sum: {sum}")