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]))