Day 18
This commit is contained in:
51
day18/part2.py
Normal file
51
day18/part2.py
Normal file
@@ -0,0 +1,51 @@
|
||||
#!/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))
|
||||
Reference in New Issue
Block a user