-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday18-2.py
62 lines (57 loc) · 1.58 KB
/
day18-2.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
from functools import reduce
def compute(l):
brak = 0
inner = []
prod = []
tmp = 0
op = "+"
flag = "num"
for i in l:
if brak == 0:
if len(inner) > 0:
if op == "+":
tmp += compute(inner)
elif op == "*":
prod.append(tmp)
tmp = compute(inner)
inner = []
flag = "op"
if flag == "num":
if i[0] != "(":
if op == "+":
tmp += int(i)
elif op == "*":
prod.append(tmp)
tmp = int(i)
flag = "op"
elif i[0] == "(":
brak += i.count("(")
inner.append(i[1:])
elif flag == "op":
op = i
flag = "num"
else:
if "(" in i:
brak += i.count("(")
inner.append(i)
elif ")" in i:
brak -= i.count(")")
if brak == 0:
inner.append(i[:-1])
else:
inner.append(i)
else:
inner.append(i)
if len(inner) > 0:
if op == "+":
tmp += compute(inner)
elif op == "*":
prod.append(tmp)
tmp = compute(inner)
prod.append(tmp)
return reduce(lambda x, y: x * y, prod)
res = 0
with open("day18-1.txt") as f:
for line in f:
res += compute(line.strip().split(" "))
print(res)