-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathday_18b.py
85 lines (72 loc) · 2.14 KB
/
day_18b.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/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 calcExprValueAdv(expr):
simplifiedEquation = deque()
while len(expr) > 1:
operand1 = int()
operand2 = int()
if expr[0] != "(":
operand1 = int(expr.popleft())
else:
operand1 = calcExprValueAdv(getSubExpr(expr))
operator = expr.popleft()
if expr[0] != "(":
operand2 = int(expr.popleft())
else:
operand2 = calcExprValueAdv(getSubExpr(expr))
if operator == "+":
expr.appendleft(str(operand1 + operand2))
elif operator == "*":
expr.appendleft(str(operand2))
simplifiedEquation.append(str(operand1))
simplifiedEquation.append(operator)
simplifiedEquation.append(expr.popleft())
return calcExprValue(simplifiedEquation)
def main():
f = open("../input/day_18_input")
sum = 0
for line in f:
line = line.strip("\n")
expr = getExpr(line)
sum += calcExprValueAdv(expr)
print(sum)
return sum
if __name__ == "__main__":
main()