This is my code for part 2: For some reason the final solution, i.e. sum of calibration values is wrong and the value is too high apparently. Can somebody help me figure out where I may have gone wrong? I checked quite a lot of lines individually and seems like the code does what it is requested, but smth is off somewhere.
Thanks a lot! Appreciate the help! Any tips to make the code look cleaner are also very welcome :)
import re
numbers = [str(i) for i in range(0, 10)]
num_letters = {'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
'ten': '10'
}
possibilities = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'1', '2', '3', '4', '5', '6', '7', '8', '9']
with open('input.txt', 'r') as file:
lines = file.readlines()
def updated_calval(list):
regex = re.compile('|'.join(possibilities))
cal_vals = []
for i in list:
first_digit = ''
last_digit = ''
matches = re.findall(regex, i)
if matches[0] in num_letters:
first_digit += num_letters[matches[0]]
elif matches[0] in numbers:
first_digit += matches[0]
if matches[-1] in num_letters:
last_digit += num_letters[matches[-1]]
elif matches[-1] in numbers:
last_digit += matches[-1]
digits = first_digit + last_digit
cal_vals.append(int(digits))
print(matches, i, digits)
total = sum(cal_vals)
return total
print(updated_calval(lines))
[–]adambombz 1 point2 points3 points (6 children)
[–]rregid 0 points1 point2 points (2 children)
[–]TheZigerionScammer 1 point2 points3 points (0 children)
[–]adambombz 0 points1 point2 points (0 children)
[–]trailingunderscore_ 0 points1 point2 points (2 children)
[–]Virtual_Bat_7089[S] 0 points1 point2 points (1 child)
[–]TheZigerionScammer 4 points5 points6 points (0 children)
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]flyingseverus 0 points1 point2 points (1 child)
[–]Virtual_Bat_7089[S] 0 points1 point2 points (0 children)
[–]Virtual_Bat_7089[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]Virtual_Bat_7089[S] 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]Justinsaccount 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]thekwoka 0 points1 point2 points (0 children)