diff options
author | Tomasz Kramkowski <tomasz@kramkow.ski> | 2023-12-01 10:30:46 +0000 |
---|---|---|
committer | Tomasz Kramkowski <tomasz@kramkow.ski> | 2023-12-01 10:30:46 +0000 |
commit | 4ef476c0e730d625a3ac8063ed08ebe69d48cb34 (patch) | |
tree | 30899fe9601668b069cc61d3063c0ff9e9f75b07 | |
parent | 5830d9407365dd4c10f0bc776d5157461c6728d1 (diff) | |
download | aoc2023-4ef476c0e730d625a3ac8063ed08ebe69d48cb34.tar.gz aoc2023-4ef476c0e730d625a3ac8063ed08ebe69d48cb34.tar.xz aoc2023-4ef476c0e730d625a3ac8063ed08ebe69d48cb34.zip |
day 1
-rw-r--r-- | 1.py | 45 |
1 files changed, 45 insertions, 0 deletions
@@ -0,0 +1,45 @@ +from sys import stdin +from itertools import chain +import re + +nums = { + "zero": 0, + "one": 1, + "two": 2, + "three": 3, + "four": 4, + "five": 5, + "six": 6, + "seven": 7, + "eight": 8, + "nine": 9, +} + +forward = re.compile("|".join(chain(nums.keys(), (str(n) for n in nums.values())))) +reverse = re.compile( + "|".join(chain((k[::-1] for k in nums.keys()), (str(n) for n in nums.values()))) +) + + +def p1_impl(s: str) -> int: + nums = [int(n) for n in s if n.isdigit()] + return nums[0] * 10 + nums[-1] + + +def p2_impl(s: str) -> int: + match = forward.search(s) + if not match: + raise ValueError + num = match.group() + first = int(nums.get(num, num)) + match = reverse.search(s[::-1]) + if not match: + raise ValueError + num = match.group()[::-1] + last = int(nums.get(num, num)) + return first * 10 + last + + +inp = [line.rstrip() for line in stdin] +print(sum(p1_impl(i) for i in inp)) +print(sum(p2_impl(i) for i in inp)) |