-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday18part2.py
49 lines (44 loc) · 1.17 KB
/
day18part2.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
38
39
40
41
42
43
44
45
46
47
48
49
import sys
result = 0
def calc(s):
oprands = []
operators = []
sub = []
for c in s:
if operators and operators[-1] == '(':
if c == ')':
operators.pop()
if operators and operators[-1] == '(':
sub.append(')')
else:
oprands.append(calc(sub))
sub = []
else:
if c == '(':
operators.append('(')
sub.append(c)
else:
if c.isdigit():
oprands.append(int(c))
else:
operators.append(c)
oprands2 = []
oprands.reverse()
operators.reverse()
while operators:
operator = operators.pop()
if operator == '+':
oprands.append(oprands.pop() + oprands.pop())
else:
oprands2.append(oprands.pop())
oprands2.append(oprands[0])
product = 1
for n in oprands2:
product *= n
return product
for line in sys.stdin:
if line == '\n':
break
line = line[: -1].replace('(', '( ').replace(')', ' )')
result += calc(line.split())
print(result)