Created
December 18, 2020 08:43
-
-
Save kung-foo/c78d2c0142d02d8611bdb075bf779bc6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import regex as re | |
bg = re.compile(r"\([^)(]*+(?:(?R)[^)(]*)*+\)", re.VERSION1) | |
src = open("input.txt", "r").readlines() | |
src2 = """ | |
1 + 2 * 3 + 4 * 5 + 6 | |
1 + (2 * 3) + (4 * (5 + 6)) | |
2 * 3 + (4 * 5) | |
5 + (8 * 3 + 9 + 3 * 4 * 3) | |
5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4)) | |
((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2 | |
""".splitlines() | |
src = [r.strip() for r in src if r.strip()] | |
def tokenize(line): | |
out = [] | |
for c in line.split(" "): | |
if c.isdigit(): | |
out.append(int(c)) | |
elif c in "+*()": | |
out.append(c) | |
return out | |
def solve(eq): | |
for m in bg.finditer(eq): | |
g = m.group() | |
eq = eq.replace(g, solve(g[1:-1])) | |
eq = tokenize(eq) | |
while "+" in eq: | |
p = eq.index("+") | |
v = eq[p - 1] + eq[p + 1] | |
eq = eq[0 : p - 1] + [v] + eq[p + 2 :] | |
while len(eq) != 1: | |
l, op, r = eq.pop(0), eq.pop(0), eq.pop(0) | |
if op == "+": | |
eq.insert(0, l + r) | |
else: | |
eq.insert(0, l * r) | |
return str(eq.pop()) | |
s = 0 | |
for line in src: | |
s += int(solve(line)) | |
print(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment