From aae14797ea0ae0e8e252aa9a6af773283111c6c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Engl=C3=B6f=20Ytterstr=C3=B6m?= Date: Fri, 1 Dec 2023 07:09:50 +0100 Subject: [PATCH] Solve 2023:01 "Trebuchet?!" Turns out re methods are non-overlapping. And in true AoC manners, no provided test cases had overlaps. Luckily for me, some of the last lines in the input contained the string "oneight", so I was able to find it out quite fast. Revisions: 1) Reverse strings to find last digit 2) Use isdigit() and skip regex. 3) Use regexp with positive look-ahead. --- 2023-python/output/day_01.py | 55 ++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 2023-python/output/day_01.py diff --git a/2023-python/output/day_01.py b/2023-python/output/day_01.py new file mode 100644 index 0000000..2f27529 --- /dev/null +++ b/2023-python/output/day_01.py @@ -0,0 +1,55 @@ +import re +from output import answer, puzzleinput + +n = 1 +title = "Trebuchet?!" + + +@answer(1, "Calibration values sum: {}, excluding spelled out digits") +def part_1(data): + def value(s): + s = [int(c) for c in s if c.isdigit()] + return s[0] * 10 + s[-1] + + return sum(value(line) for line in data) + + +@answer(2, "Calibration values sum: {}, including spelled out digits") +def part_2(data): + mp = { + "one": 1, + "two": 2, + "three": 3, + "four": 4, + "five": 5, + "six": 6, + "seven": 7, + "eight": 8, + "nine": 9, + } + + def value(l): + s = [ + int(c) if c.isdigit() else mp[c] + for c in re.findall( + r"(?=(\d|one|two|three|four|five|six|seven|eight|nine))", l + ) + ] + return s[0] * 10 + s[-1] + + return sum(value(line) for line in data) + + +@puzzleinput(n) +def parse_input(data): + return data.split() + + +if __name__ == "__main__": + parsed = parse_input() + + a = part_1(parsed) + b = part_2(parsed) + + assert a == 54634 + assert b == 53855