36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
def getDigitsOfLine(line) -> int:
|
|
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
|
spelled_digits = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
|
|
first_digit = 0
|
|
last_digit: int = None
|
|
for i in range(len(line)):
|
|
if line[i] in digits:
|
|
if first_digit == 0:
|
|
first_digit = digits.index(line[i])
|
|
else:
|
|
last_digit = digits.index(line[i])
|
|
else:
|
|
spelled: str = line[i]
|
|
for j in range(i+1, len(line)):
|
|
spelled += line[j]
|
|
if spelled in spelled_digits:
|
|
if first_digit == 0:
|
|
first_digit = spelled_digits.index(spelled)
|
|
else:
|
|
last_digit = spelled_digits.index(spelled)
|
|
break
|
|
if last_digit == None:
|
|
last_digit = first_digit
|
|
number = (first_digit * 10) + last_digit
|
|
print(f'Number found: {number}')
|
|
return number
|
|
|
|
lines = open('values2', 'r').readlines()
|
|
|
|
number_sum = 0
|
|
|
|
for line in lines:
|
|
if line != '':
|
|
number_sum += getDigitsOfLine(line)
|
|
|
|
print(f'Sum: {number_sum}') # 281 |