Files
adventofcode2023/1/trebuchet.py
2023-12-02 14:09:24 +01:00

48 lines
1.4 KiB
Python

from aocd.models import Puzzle
from aocd import submit
def calibrate(line: list) -> int:
"""
Solve part a.
- Filter all digits from the line
- Add the first and the last and return result
"""
# filter digits
digits = [c for c in line if c.isdigit()]
# return the sum of the first and the last digit
return int(digits[0] + digits[-1])
def translate(line: str) -> str:
"""
Solve part b.
- Look for spelled out numbers
- replace them by a string where the first and last digit is preserved
- due to the fact that numbers can be part of each other
- return the translation and use the calibratoin function of part a.
"""
numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
translation = ["o1e", "t2o", "t3e", "f4r", "f5e", "s6x", "s7n", "e8t", "n9e"]
for n, t in zip(numbers, translation):
while n in line:
line = line.replace(n, t)
return line
if __name__ == "__main__":
# get puzzle and parse data
puzzle = Puzzle(year=2023, day=1)
# part a:
answer_a = sum(calibrate(l) for l in puzzle.input_data.split("\n"))
print(f"{answer_a}")
submit(answer_a, part="a", day=1, year=2023)
# part b:
answer_b = sum(calibrate(translate(l)) for l in puzzle.input_data.split("\n"))
print(f"{answer_b}")
submit(answer_b, part="b", day=1, year=2023)