-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.py
37 lines (32 loc) · 857 Bytes
/
18.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from collections import deque
import math
ops = {'+': lambda x, y: x+y,
'*': lambda x, y: x*y}
def solve(i):
nums, symbols = deque(), deque()
while i < len(expression):
c = expression[i]
if c == ' ':
i += 1
continue
elif c == '(':
i, val = solve(i + 1)
nums.append(val)
elif c == ')':
break
elif c in '+*':
symbols.append(c)
else: # digit
nums.append(int(c))
i += 1
multiplicands = [nums.popleft()]
for op in symbols:
num = nums.popleft()
if op == '+':
num += multiplicands.pop()
multiplicands.append(num)
return i, math.prod(multiplicands)
result = 0
for expression in open('18.txt').read().splitlines():
result += solve(0)[1]
print(result)