-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpartOne.py
More file actions
67 lines (49 loc) · 1.33 KB
/
partOne.py
File metadata and controls
67 lines (49 loc) · 1.33 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
from typing import List, Tuple, Union
def parse_expression(expression: str) -> Tuple[List, int]:
o = []
if len(expression) == 0:
return o, 0
ptr = 0
while ptr < len(expression):
char = expression[ptr]
if char == "(":
nl, idx = parse_expression(expression[ptr + 1 :])
o.append(nl)
ptr += idx
elif char == ")":
return o, ptr + 1
else:
o.append(char)
ptr += 1
return o, 0
def calc_to_int(x: Union[list, str]) -> int:
if type(x) == list:
return calculate(x)
else:
return int(x)
def calculate(expression: List) -> int:
n = calc_to_int(expression[0])
ptr = 1
while ptr < len(expression):
op = expression[ptr]
x = calc_to_int(expression[ptr + 1])
if op == "+":
n += x
elif op == "-":
n -= x
elif op == "*":
n *= x
elif op == "/":
n /= x
else:
raise ValueError(f"unknown operator '{op}'")
ptr += 2
return n
def partOne(instr: str) -> int:
expressions = [
parse_expression(list(x.replace(" ", "")))[0] for x in instr.strip().split("\n")
]
sigma = 0
for expression in expressions:
sigma += calculate(expression)
return sigma