Created
December 18, 2020 17:32
-
-
Save aledesole/9fea7fd68ed14749f75fa936e61fc1df to your computer and use it in GitHub Desktop.
Advent of code 2020, Day 18, Python3.9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import stdin | |
from operator import add, mul | |
from re import findall | |
def arg(cont, ts): | |
res, ts = cont(ts[1:]) if ts[0] == '(' else (int(ts[0]), ts) | |
return res, ts[1:] | |
def parse(ops, term, cont, ts): | |
lh, ts = term(cont, ts) | |
while ts and (ts[0] in ops): | |
op, ts = (add if ts[0] == '+' else mul, ts[1:]) | |
rh, ts = term(cont, ts) | |
lh = op(lh, rh) | |
return lh, ts | |
def part1(ts): | |
return parse("+*", arg, part1, ts) | |
def part2(ts): | |
def part2inner(cont, ts): | |
return parse("+", arg, cont, ts) | |
return parse("*", part2inner, part2, ts) | |
tokens = [findall('\(|\)|\*|\+|\d+', l) for l in stdin] | |
solve = lambda part: sum(v for v, _ in (part(ts) for ts in tokens)) | |
print(solve(part1), solve(part2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment