Files
python-aoc-2020/day18/part2.py
Sebastian Seedorf 425451a821 Day 18
2020-12-18 13:57:57 +01:00

52 lines
1.2 KiB
Python

#!/usr/bin/env python3
import re
lines = (x.strip().replace(" ", "") for x in open("input.txt"))
def calc(a, b, pop):
return a+b if pop == "+" else a*b
def pres(pop):
if pop == "+":
return 2
if pop == "*":
return 1
return 0
def evaluate(line):
stack = []
postfix = [0]
pos = -1
for char in "("+line+")":
pos += 1
if char == '(':
stack.append("(")
elif char == ')':
while True:
pop = stack.pop()
if pop == '(':
break
a, b = postfix.pop(), postfix.pop()
postfix.append(calc(a, b, pop))
elif char in "0123456789":
postfix[-1] = postfix[-1] * 10 + int(char)
elif char in "*+":
while True:
pop = stack.pop()
if pres(pop) <= pres(char):
stack.append(pop)
stack.append(char)
postfix.append(0)
break
a, b = postfix.pop(), postfix.pop()
postfix.append(calc(a, b, pop))
else:
raise SystemError("Invalid char: "+char)
return postfix[0]
print(sum(evaluate(line) for line in lines))