summaryrefslogtreecommitdiffstats
path: root/21.py
blob: 40967a988328247ba8dda2be32725ec3d6d754e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from operator import add, sub, mul, truediv, eq
from subprocess import run, PIPE
from utils import open_day
from sympy import solve, Symbol

monkeys = {}
with open_day(21) as f:
    for line in f:
        target, expr = line.rstrip().split(': ')
        expr = expr.split(' ')
        if len(expr) == 1:
            expr = int(expr[0])
        monkeys[target] = expr

ops = { '+': add, '-': sub, '*': mul, '/': truediv }

def eval_monkey(m):
    expr = monkeys[m]
    if isinstance(expr, int) or isinstance(expr, Symbol):
        return expr
    return ops[expr[1]](eval_monkey(expr[0]), eval_monkey(expr[2]))

print(int(eval_monkey('root')))
monkeys['humn'] = Symbol('humn')
monkeys['root'][1] = '-'
print(int(solve(eval_monkey('root'), monkeys['humn'])[0]))