-
Notifications
You must be signed in to change notification settings - Fork 9
/
day_18a.py
62 lines (49 loc) · 1.34 KB
/
day_18a.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
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/python3
from collections import deque
def getExpr(line):
expr = deque()
for char in line:
if char != " ":
expr.append(char)
return expr
def getSubExpr(expr):
bracket_count = 0
expr.popleft()
new_expr = deque()
while bracket_count > 0 or expr[0] != ")":
if expr[0] == "(":
bracket_count += 1
elif expr[0] == ")":
bracket_count -= 1
new_expr.append(expr[0])
expr.popleft()
expr.popleft()
return new_expr
def calcExprValue(expr):
while len(expr) > 1:
operand1 = int()
operand2 = int()
if expr[0] != "(":
operand1 = int(expr.popleft())
else:
operand1 = calcExprValue(getSubExpr(expr))
operator = expr.popleft()
if expr[0] != "(":
operand2 = int(expr.popleft())
else:
operand2 = calcExprValue(getSubExpr(expr))
if operator == "+":
expr.appendleft(str(operand1 + operand2))
elif operator == "*":
expr.appendleft(str(operand1 * operand2))
return int(expr[0])
def main():
f = open("../input/day_18_input")
sum = 0
for line in f:
line = line.strip("\n")
expr = getExpr(line)
sum += calcExprValue(expr)
print(sum)
if __name__ == "__main__":
main()