summary refs log tree commit diff
path: root/22.21/part2.py
blob: 248a7fd92be799b0092333cf8eeada1f5982d827 (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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from sys import stdin

monkeys = {}

for line in stdin:
	out = line[:4]
	parts = line[6:].split()
	if len(parts) == 1: parts = int(parts[0])
	monkeys[out] = parts

def f(x):
	monks = monkeys.copy()
	monks["root"][1] = '-'
	monks["humn"] = int(x)
	def get(k):
		m = monks[k]
		if type(m) != int:
			a = get(m[0])
			b = get(m[2])
			op = m[1]
			if op == '+': m = a + b
			if op == '-': m = a - b
			if op == '*': m = a * b
			if op == '/': m = a / b
			monks[k] = m
		return m
	return get("root")

x = 0
# newton
while True:
	a = f(x)
	print(x, a)
	if a == 0: break

	d = a - f(x-1)
	if d == 0:
		x += 1
		continue
	x = x - int(a/d)