You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.5 KiB
Python

4 years ago
import re
example1 = '1 + 2 * 3 + 4 * 5 + 6'
example2 = '1 + (2 * 3) + (4 * (5 + 6))'
example3 = '2 * 3 + (4 * 5)'
example4 = '5 + (8 * 3 + 9 + 3 * 4 * 3)'
example5 = '5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))'
example6 = '((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2'
with open('input') as f:
expressions = f.readlines()
def calc(op, a, b):
if op == '+':
return a + b
elif op == '*':
return a * b
else:
raise Exception(f'Operator "{op}" not known')
def solve(line):
num_stack = [0]
op_stack = ['+']
for char in line:
if char in [' ', '\n']:
continue
if char == '(':
num_stack.append(0)
op_stack.append('+')
elif char == ')':
op = op_stack.pop()
a = num_stack.pop()
b = num_stack.pop()
num_stack.append(calc(op, a, b))
elif char in ['+', '*']:
op_stack.append(char)
elif re.match('[0-9]', char):
num = int(char)
num_stack.append(int(char))
op = op_stack.pop()
a = num_stack.pop()
b = num_stack.pop()
num_stack.append(calc(op, a, b))
# print(num_stack, op_stack)
return num_stack.pop()
print(example1, '=', solve(example1))
print(example2, '=', solve(example2))
print(example3, '=', solve(example3))
print(example4, '=', solve(example4))
print(example5, '=', solve(example5))
print(example6, '=', solve(example6))
print('Solution')
print(sum(map(solve, expressions)))