-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.py
71 lines (60 loc) · 1.42 KB
/
18.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
from lib import *
input = read_input(2020, 18)
lines = input.splitlines()
def evaluate1(expr):
new_expr = ""
cnt = 0
buffer = ""
for c in expr.replace(" ", ""):
if c == "(":
if cnt:
buffer += c
cnt += 1
elif c == ")":
cnt -= 1
if cnt:
buffer += c
else:
new_expr += str(evaluate1(buffer))
buffer = ""
elif cnt:
buffer += c
else:
new_expr += c
out = 0
buffer = 0
op = False
for c in new_expr + " ":
if c.isnumeric():
buffer = buffer * 10 + int(c)
continue
if op:
out *= buffer
else:
out += buffer
buffer = 0
op = c == "*"
return out
print(sum(map(evaluate1, lines)))
def evaluate2(expr):
new_expr = ""
cnt = 0
buffer = ""
for c in expr.replace(" ", ""):
if c == "(":
if cnt:
buffer += c
cnt += 1
elif c == ")":
cnt -= 1
if cnt:
buffer += c
else:
new_expr += str(evaluate2(buffer))
buffer = ""
elif cnt:
buffer += c
else:
new_expr += c
return math.prod(sum(map(int, x.split("+"))) for x in new_expr.split("*"))
print(sum(map(evaluate2, lines)))