This commit is contained in:
Sebastian Seedorf
2020-12-18 13:57:57 +01:00
parent bc46bbdc14
commit 425451a821
3 changed files with 455 additions and 0 deletions

31
day18/part1.py Normal file
View File

@@ -0,0 +1,31 @@
#!/usr/bin/env python3
import re
lines = (x.strip().replace(" ", "") for x in open("input.txt"))
RE_PLUS = re.compile(r"\+")
RE_MUL = re.compile(r"\*")
RE_NUM = re.compile(r"^\d")
RE_PAR = re.compile(r"^\((.*?)\)$")
def evaluate(line):
stack = [0]
num = 0
op = ['+']
for char in line:
if char in '+*':
stack[-1] = stack[-1]*num if op[-1] == '*' else stack[-1]+num
op[-1] = char
num = 0
elif char == '(':
stack.append(0)
op.append('+')
elif char == ')':
stack[-1] = stack[-1]*num if op[-1] == '*' else stack[-1]+num
num = stack.pop()
op.pop()
else:
num = num*10 + int(char)
stack[-1] = stack[-1]*num if op[-1] == '*' else stack[-1]+num
return stack[0]
print(sum(evaluate(line) for line in lines))