-
Notifications
You must be signed in to change notification settings - Fork 0
/
day18.py
84 lines (73 loc) · 1.84 KB
/
day18.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
with open("input/day18", "r") as input:
data = input.read().split("\n")
data.pop()
def handleOp(acc, val, op):
if op == '+':
return acc + val
elif op == '*':
return acc * val
else:
raise "op"
def calculate_pt1(line, i):
acc = 0
val = ''
op = '+'
while i < len(line):
c = line[i]
if c == ' ':
if val != '':
acc = handleOp(acc, int(val), op)
val = ''
elif c == '+' or c == '*':
op = c
i += 1
elif "0" <= c <= "9":
val += c
elif c == '(':
subResult = calculate_pt1(line, i + 1)
acc = handleOp(acc, subResult[0], op)
i = subResult[1]
elif c == ')':
break
else:
raise "c"
i += 1
if val != '':
acc = handleOp(acc, int(val), op)
return [acc, i]
def calculate_pt2(line, i):
acc = 0
val = ''
op = '+'
factors = []
while i < len(line):
c = line[i]
if c == ' ':
if val != '':
acc = handleOp(acc, int(val), op)
val = ''
elif c == '+':
op = c
i += 1
elif c == '*':
factors.append(acc)
acc = 0
i += 1
elif "0" <= c <= "9":
val += c
elif c == '(':
subResult = calculate_pt2(line, i + 1)
acc = handleOp(acc, subResult[0], op)
i = subResult[1]
elif c == ')':
break
else:
raise "c"
i += 1
if val != '':
acc = handleOp(acc, int(val), op)
for f in factors:
acc *= f
return [acc, i]
print(sum([calculate_pt1(entry, 0)[0] for entry in data]))
print(sum([calculate_pt2(entry, 0)[0] for entry in data]))