#!/usr/bin/env python3 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): return operators[pop][1](a, b) def prec(pop): return operators.get(pop, [0])[0] def evaluate(line): stack = [] postfix = [0] for char in "("+line+")": if char.isdigit(): postfix[-1] = postfix[-1] * 10 + int(char) elif char == '(': stack.append(char) elif char == ')': while prec(stack[-1]) > 0: postfix.append(calc(postfix.pop(), postfix.pop(), stack.pop())) stack.pop() elif char in operators: while prec(stack[-1]) > prec(char): postfix.append(calc(postfix.pop(), postfix.pop(), stack.pop())) stack.append(char) postfix.append(0) else: raise SystemError("Invalid char: "+char) return postfix[0] print(sum(evaluate(line) for line in lines))