From 042085cc4bebcc6f951f87ab27d45b3c8322dd1d Mon Sep 17 00:00:00 2001 From: felixm Date: Fri, 1 Dec 2023 22:51:14 -0500 Subject: [PATCH] Do day 1. --- d1.py | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 d1.py diff --git a/d1.py b/d1.py new file mode 100644 index 0000000..543fa39 --- /dev/null +++ b/d1.py @@ -0,0 +1,89 @@ +import re + +EXAMPLE = """ +1abc2 +pqr3stu8vwx +a1b2c3d4e5f +treb7uchet +""" + +EXAMPLE2 = """ +two1nine +eightwothree +abcone2threexyz +xtwone3four +4nineeightseven2 +zoneight234 +7pqrstsixteen +""" + +WORD_TO_DIGIT = { + "1": "1", + "2": "2", + "3": "3", + "4": "4", + "5": "5", + "6": "6", + "7": "7", + "8": "8", + "9": "9", + "one": "1", + "two": "2", + "three": "3", + "four": "4", + "five": "5", + "six": "6", + "seven": "7", + "eight": "8", + "nine": "9", +} + +def get_sum(text: str): + s = 0 + r = re.compile(r"[^\d]") + for line in text.splitlines(): + if line.strip() == "": + continue + line = r.sub("", line) + s += int(line[0] + line[-1]) + return s + +def get_sum2(text: str): + s = 0 + for line in text.splitlines(): + if line.strip() == "": + continue + + first = "" + for i in range(len(line)): + for (word, digit) in WORD_TO_DIGIT.items(): + if word == line[i:i + len(word)]: + first = digit + break + if first != "": + break + + last = "" + for i in range(len(line), 0, -1): + for (word, digit) in WORD_TO_DIGIT.items(): + if word == line[i - len(word):i]: + last = digit + break + if last != "": + break + + v = first + last + s += int(v) + return s + +if __name__ == "__main__": + assert(get_sum(EXAMPLE) == 142) + assert(get_sum2(EXAMPLE2) == 281) + with open("i1.txt", 'r') as f: + text = f.read() + r = get_sum(text) + print(r) + assert(r == 55386) + r = get_sum2(text) + print(r) + assert(r == 54824)