From cef93e325ff5ba5f32e85d28075902204755e48e Mon Sep 17 00:00:00 2001 From: Andrew Ekstedt Date: Tue, 20 Dec 2022 21:56:12 -0800 Subject: [PATCH] day 21 python part 1 solution --- day21/sol.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 day21/sol.py diff --git a/day21/sol.py b/day21/sol.py new file mode 100644 index 0000000..6e5ba8e --- /dev/null +++ b/day21/sol.py @@ -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']))