day 21 python part 1 solution

main
magical 2022-12-20 21:56:12 -08:00
parent c4d168689f
commit cef93e325f
1 changed files with 39 additions and 0 deletions

39
day21/sol.py 100644
View File

@ -0,0 +1,39 @@
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']))