-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
72 lines (49 loc) · 1.65 KB
/
main.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
from src.common.file_utils import get_path, read_lines
def part_one(filename: str) -> int:
lines = read_lines(get_path(__file__, filename))
return sum([evaluate(l, evaluate_exp1) for l in lines])
def part_two(filename: str) -> int:
lines = read_lines(get_path(__file__, filename))
return sum([evaluate(l, evaluate_exp2) for l in lines])
def evaluate(exp, evaluate_exp_func):
exp = [c for c in exp.replace(" ", "")]
i, last_open = 0, None
while i < len(exp):
if exp[i] == "(":
last_open = i
elif exp[i] == ")":
exp = exp[:last_open] + \
[evaluate_exp_func(exp[last_open+1:i])] + exp[i+1:]
i, last_open = 0, None
continue
i += 1
return evaluate_exp_func(exp)
def evaluate_exp1(exp):
res, current_op = 0, "+"
for i in range(len(exp)):
c = str(exp[i])
if c in ["+", "*"]:
current_op = c
elif c.isdigit():
res = operate(current_op)(res, int(c))
return res
def evaluate_exp2(exp):
while len(exp) > 1:
for op in ["+", "*"]:
while op in exp:
idx = exp.index(op)
val = operate(op)(int(exp[idx-1]), int(exp[idx+1]))
exp = exp[:idx - 1] + [val] + exp[idx+2:]
return exp[-1]
def operate(op):
if op == "+":
return lambda a, b: a + b
if op == "*":
return lambda a, b: a * b
if __name__ == '__main__':
print("---Part One---")
part_one_res = part_one("input.txt")
print(part_one_res)
print("---Part Two---")
part_two_res = part_two("input.txt")
print(part_two_res)