Day 18 (cleanup part 2)

This commit is contained in:
Sebastian Seedorf
2020-12-18 14:28:04 +01:00
parent 425451a821
commit 51c3746627

View File

@@ -1,48 +1,37 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import re
lines = (x.strip().replace(" ", "") for x in open("input.txt")) lines = (x.strip().replace(" ", "") for x in open("input.txt"))
operators = {
"+": [2, lambda a, b: a+b],
"*": [1, lambda a, b: a*b],
}
def calc(a, b, pop): def calc(a, b, pop):
return a+b if pop == "+" else a*b return operators[pop][1](a, b)
def pres(pop): def pres(pop):
if pop == "+": return operators.get(pop, [0])[0]
return 2
if pop == "*":
return 1
return 0
def evaluate(line): def evaluate(line):
stack = [] stack = []
postfix = [0] postfix = [0]
pos = -1
for char in "("+line+")": for char in "("+line+")":
pos += 1 if char.isdigit():
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) postfix[-1] = postfix[-1] * 10 + int(char)
elif char == '(':
stack.append(char)
elif char == ')':
while pres(stack[-1]) > 0:
postfix.append(calc(postfix.pop(), postfix.pop(), stack.pop()))
stack.pop() # remove (
elif char in "*+": elif char in "*+":
while True: while pres(stack[-1]) > pres(char):
pop = stack.pop() postfix.append(calc(postfix.pop(), postfix.pop(), stack.pop()))
if pres(pop) <= pres(char):
stack.append(pop)
stack.append(char) stack.append(char)
postfix.append(0) postfix.append(0)
break
a, b = postfix.pop(), postfix.pop()
postfix.append(calc(a, b, pop))
else: else:
raise SystemError("Invalid char: "+char) raise SystemError("Invalid char: "+char)
return postfix[0] return postfix[0]