1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- import logging
- import re
-
- from functools import reduce
- from itertools import pairwise
- from sys import stdout
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- LOG_FILENAME = "./day03-1.log"
- INPUT_FILENAME = "./input03.txt"
-
- logger = logging.Logger(__name__)
- formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
- sh = logging.StreamHandler(stdout)
- sh.setLevel(logging.INFO)
- sh.setFormatter(formatter)
- fh = logging.FileHandler(LOG_FILENAME, mode="w", encoding="utf-8")
- fh.setLevel(logging.DEBUG)
- fh.setFormatter(formatter)
- logger.addHandler(sh)
- logger.addHandler(fh)
-
- def multiply_pair(s):
- pair = [int(x) for x in s[4:-1].split(",")]
- return reduce(lambda x,y: x*y, pair, 1)
-
- def main():
- with open(INPUT_FILENAME, "r") as f:
- line = "".join(f.readlines())
-
- MUL_REGEX = r"((do|don't)\(\)|mul\(\d{1,3},\d{1,3}\))"
- matches = re.findall(MUL_REGEX, line)
- ops = [x[0] for x in matches]
- logger.info(ops[:25])
- good_ops = []
- toggle = True
- for o in ops:
- if not toggle and o == "do()":
- toggle = True
- continue
- if toggle:
- if o == "don't()":
- toggle = False
- continue
- if "mul" in o:
- good_ops.append(o)
-
- total_sum = reduce(lambda x,y: x+y, map(multiply_pair, good_ops))
- logger.info(f"Total sum: {total_sum}")
-
-
- if __name__ == "__main__":
- main()
|