-
Notifications
You must be signed in to change notification settings - Fork 1
/
21_Monkey_Math.py
52 lines (46 loc) · 1.53 KB
/
21_Monkey_Math.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from aoc import *
import re
monkeys = dict(read(sep=r': '))
values = {}
def solve(cur: str) -> int | None:
if cur in values:
return values[cur]
expr = monkeys[cur]
if isinstance(expr, int):
values[cur] = expr
return expr
if expr == 'INPUT':
return None
l, op, r = expr.split()
lv, rv = solve(l), solve(r)
if lv is None or rv is None:
return None
match op:
case '+': return lv + rv
case '-': return lv - rv
case '*': return lv * rv
case '/': return lv // rv
print('Star 1:', solve('root'))
monkeys['root'] = monkeys['root'][:5] + '=' + monkeys['root'][6:]
monkeys['humn'] = 'INPUT'
values = {}
def solve_for_humn(cur: str, expected: int) -> int:
expr = monkeys[cur]
if expr == 'INPUT':
return expected
l, op, r = expr.split()
lv, rv = solve(l), solve(r)
if lv is None:
match op:
case '=': return solve_for_humn(l, rv)
case '+': return solve_for_humn(l, expected - rv)
case '-': return solve_for_humn(l, expected + rv)
case '*': return solve_for_humn(l, expected // rv)
case '/': return solve_for_humn(l, expected * rv)
match op:
case '=': return solve_for_humn(r, lv)
case '+': return solve_for_humn(r, expected - lv)
case '-': return solve_for_humn(r, lv - expected)
case '*': return solve_for_humn(r, expected // lv)
case '/': return solve_for_humn(r, lv // expected)
print('Star 2:', solve_for_humn('root', 0))