40 lines
825 B
Python
40 lines
825 B
Python
|
import operator
|
||
|
|
||
|
lines = []
|
||
|
for line in open("input"):
|
||
|
lines.append(line.split())
|
||
|
|
||
|
|
||
|
unused = lines
|
||
|
scope = {}
|
||
|
while unused:
|
||
|
lines, unused = unused, []
|
||
|
for words in lines:
|
||
|
refs = [x for x in words[1:] if x.isalpha()]
|
||
|
if any(r not in scope for r in refs):
|
||
|
unused.append(words)
|
||
|
continue
|
||
|
dst = words[0].rstrip(':')
|
||
|
if len(words) == 2:
|
||
|
_, src = words
|
||
|
scope[dst] = int(src)
|
||
|
continue
|
||
|
_, x, op, y = words
|
||
|
scope[dst] = (op, scope[x], scope[y])
|
||
|
|
||
|
optab = {
|
||
|
'*': operator.mul,
|
||
|
'/': operator.floordiv,
|
||
|
'+': operator.add,
|
||
|
'-': operator.sub,
|
||
|
}
|
||
|
|
||
|
def eval(x):
|
||
|
if type(x) == int:
|
||
|
return x
|
||
|
op = x[0]
|
||
|
args = [eval(a) for a in x[1:]]
|
||
|
return optab[op](*args)
|
||
|
|
||
|
print(eval(scope['root']))
|