#!/usr/bin/env python3 # https://adventofcode.com/2023/day/1 NUMBER_DICT = { "one": "o1e", "two": "t2o", "three": "t3e", "four": "4", "five": "5e", "six": "6", "seven": "7n", "eight": "e8t", "nine": "n9e", } def get_lines(filename: str) -> list: with open(filename, "r") as file: return [line.strip() for line in file.readlines()] def get_cal_val(line: str) -> int: found_first = False first = "" last = "" for test_char in line: if test_char.isdigit(): if found_first: last = test_char else: first = test_char found_first = True if last == "": last = first return int(first + last) 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) 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__': main()