From 52ecb598bc099c8053896a638d7c014d052787a3 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Fri, 1 Dec 2023 12:13:44 +0000 Subject: [PATCH] 2023: d01: ex2: add solution --- 2023/d01/ex2/ex2.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100755 2023/d01/ex2/ex2.py diff --git a/2023/d01/ex2/ex2.py b/2023/d01/ex2/ex2.py new file mode 100755 index 0000000..2412098 --- /dev/null +++ b/2023/d01/ex2/ex2.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +import sys + + +def solve(input: list[str]) -> int: + def extract_digits(line: str) -> list[int]: + # Just do a search and replace to simplify our lives + digits = { + "one": 1, + "two": 2, + "three": 3, + "four": 4, + "five": 5, + "six": 6, + "seven": 7, + "eight": 8, + "nine": 9, + } + # The solution expects "sevenine" to translate to 79, so keep first/last character + # as a work-around. + for word, value in digits.items(): + line = line.replace(word, word[0] + str(value) + word[-1]) + return [int(c) for c in line if c.isdigit()] + + def value(line: str) -> int: + digits = extract_digits(line) + return digits[0] * 10 + digits[-1] + + return sum(value(line) for line in input) + + +def main() -> None: + input = sys.stdin.read().splitlines() + print(solve(input)) + + +if __name__ == "__main__": + main()