-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpartTwo.py
More file actions
70 lines (52 loc) · 1.64 KB
/
Copy pathpartTwo.py
File metadata and controls
70 lines (52 loc) · 1.64 KB
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
import re
def is_number(str):
try:
int(str)
return True
except ValueError:
return False
def is_name(str):
return re.match("\w+", str)
def peek(stack):
return stack[-1] if stack else None
def apply_operator(operators, values):
operator = operators.pop()
right = values.pop()
left = values.pop()
values.append(eval("{0}{1}{2}".format(left, operator, right)))
def greater_precedence(op1, op2):
precedences = {"+": 2, "-": 0, "*": 1, "/": 1}
return precedences[op1] > precedences[op2]
def evaluate(expression):
tokens = re.findall("[+/*()-]|\d+", expression)
values = []
operators = []
for token in tokens:
if is_number(token):
values.append(int(token))
elif token == "(":
operators.append(token)
elif token == ")":
top = peek(operators)
while top is not None and top != "(":
apply_operator(operators, values)
top = peek(operators)
operators.pop() # Discard the '('
else:
# Operator
top = peek(operators)
while (
top is not None and top not in "()" and greater_precedence(top, token)
):
apply_operator(operators, values)
top = peek(operators)
operators.append(token)
while peek(operators) is not None:
apply_operator(operators, values)
return values[0]
def partTwo(instr: str) -> int:
expressions = instr.strip().split("\n")
sigma = 0
for expression in expressions:
sigma += evaluate(expression)
return sigma