Day 18 (glamorized)

This commit is contained in:
Sebastian Seedorf
2020-12-19 00:48:12 +01:00
parent 51c3746627
commit af2e297a24
2 changed files with 6 additions and 10 deletions

View File

@@ -1,11 +1,6 @@
#!/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"))
RE_PLUS = re.compile(r"\+")
RE_MUL = re.compile(r"\*")
RE_NUM = re.compile(r"^\d")
RE_PAR = re.compile(r"^\((.*?)\)$")
def evaluate(line): def evaluate(line):
stack = [0] stack = [0]
@@ -28,4 +23,5 @@ def evaluate(line):
stack[-1] = stack[-1]*num if op[-1] == '*' else stack[-1]+num stack[-1] = stack[-1]*num if op[-1] == '*' else stack[-1]+num
return stack[0] return stack[0]
print(sum(evaluate(line) for line in lines)) print(sum(evaluate(line) for line in lines))

View File

@@ -11,7 +11,7 @@ def calc(a, b, pop):
return operators[pop][1](a, b) return operators[pop][1](a, b)
def pres(pop): def prec(pop):
return operators.get(pop, [0])[0] return operators.get(pop, [0])[0]
@@ -24,11 +24,11 @@ def evaluate(line):
elif char == '(': elif char == '(':
stack.append(char) stack.append(char)
elif char == ')': elif char == ')':
while pres(stack[-1]) > 0: while prec(stack[-1]) > 0:
postfix.append(calc(postfix.pop(), postfix.pop(), stack.pop())) postfix.append(calc(postfix.pop(), postfix.pop(), stack.pop()))
stack.pop() # remove ( stack.pop()
elif char in "*+": elif char in operators:
while pres(stack[-1]) > pres(char): while prec(stack[-1]) > prec(char):
postfix.append(calc(postfix.pop(), postfix.pop(), stack.pop())) postfix.append(calc(postfix.pop(), postfix.pop(), stack.pop()))
stack.append(char) stack.append(char)
postfix.append(0) postfix.append(0)