solve day 01 part 2

This commit is contained in:
Heiko Ludwig 2023-12-01 21:36:24 +01:00
parent d270ffbf1a
commit d8fcaedfda
5 changed files with 59 additions and 6 deletions

View file

@ -2,7 +2,17 @@
# https://adventofcode.com/2023/day/1
import re
NUMBER_DICT = {
"one": "on1e",
"two": "tw2o",
"three": "thr3ee",
"four": "fo4ur",
"five": "fi5ve",
"six": "si6x",
"seven": "sev7en",
"eight": "ei8ght",
"nine": "ni9ne",
}
def get_lines(filename: str) -> list:
@ -26,13 +36,28 @@ def get_cal_val(line: str) -> int:
return int(first + last)
def main():
# lines = get_lines("test-input.txt")
lines = get_lines("input.txt")
def replace_digit_strings(line: str) -> str:
for digit in NUMBER_DICT.keys():
line = line.replace(digit, NUMBER_DICT[digit])
return line
def get_sum_cal_val(lines: list, spelled_out: bool) -> int:
sum_cal_val = 0
for line in lines:
if spelled_out:
sum_cal_val += get_cal_val(replace_digit_strings(line))
else:
sum_cal_val += get_cal_val(line)
print(f"Part 1: The sum of all calibration values is {sum_cal_val}.")
return sum_cal_val
def main():
lines = get_lines("input.txt")
sum_cal_val = get_sum_cal_val(lines, False)
print(f"Part 1: The sum of all calibration values is: {sum_cal_val}")
sum_cal_val = get_sum_cal_val(lines, True)
print(f"Part 2: The sum of all calibration values is: {sum_cal_val}")
if __name__ == '__main__':

7
day_01/test-input2.txt Normal file
View file

@ -0,0 +1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen

1
day_01/test-input3.txt Normal file
View file

@ -0,0 +1 @@
2

View file

@ -14,6 +14,26 @@ class TestThing(unittest.TestCase):
self.assertEqual(program.get_cal_val("3a2c3er"), 33)
self.assertEqual(program.get_cal_val("1234567"), 17)
self.assertEqual(program.get_cal_val("asdw3wemr"), 33)
self.assertEqual(program.get_cal_val("th95"), 95)
self.assertEqual(program.get_cal_val("g2"), 22)
self.assertEqual(program.get_cal_val("2"), 22)
def testReplaceDigitStrings(self):
self.assertEqual(program.replace_digit_strings("one"), "on1e")
self.assertEqual(program.replace_digit_strings("twosdftwo"), "tw2osdftw2o")
self.assertEqual(program.replace_digit_strings("zeightwosixa"), "zei8ghtw2osi6xa")
self.assertEqual(program.replace_digit_strings("4three2ffivee"), "4thr3ee2ffi5vee")
self.assertEqual(program.replace_digit_strings("onetwo"), "on1etw2o")
def testSumCalValPart1(self):
lines = program.get_lines("test-input1.txt")
sum_cal_val = program.get_sum_cal_val(lines, False)
self.assertEqual(sum_cal_val, 142)
def testSumCalValPart2(self):
lines = program.get_lines("test-input2.txt")
sum_cal_val = program.get_sum_cal_val(lines, True)
self.assertEqual(sum_cal_val, 281)
if __name__ == '__main__':