Skip to content
advent of code 2020

day 18

operation order

approach

a small tokenizer turns each expression into numbers, operators and parentheses. evaluate is the shunting-yard algorithm with a value stack and an operator stack: before pushing an operator, it applies every operator on the stack with greater or equal precedence; a closing parenthesis applies everything back to the matching (. consume pops one operator and two values and pushes the result.

the precedence table is a parameter, which is all the two parts change. part 1 gives + and * the same precedence, so they evaluate left to right. part 2 gives + the higher one.

the trick

shunting yard with the precedence table passed in: both parts are the same evaluator with different numbers.

python
def part1(l = exprs):
    prec = {'+':0, '*':0}
    return sum(map(lambda x: evaluate(x, prec), l))

def part2(l = exprs):
    prec = {'+':1, '*':0}
    return sum(map(lambda x: evaluate(x, prec), l))