-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.py
56 lines (40 loc) · 1.15 KB
/
part2.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
def myeval_plus(string, i, j):
result = 0
buff = ""
while i < j:
if string[i] == '+':
result += int(buff)
buff = ""
elif string[i] == '(':
k = i
opened = 1
while opened > 0:
i += 1
opened += 1 if string[i] == '(' else -1 if string[i] == ')' else 0
buff = myeval_multiply(string, k + 1, i)
else:
buff += string[i]
i += 1
if buff:
result += int(buff)
return result
def myeval_multiply(string, i, j):
result = 1
k = i
while i < j:
if string[i] == '*':
result *= myeval_multiply(string, k, i)
k = i + 1
elif string[i] == '(':
opened = 1
while opened > 0:
i += 1
opened += 1 if string[i] == '(' else -1 if string[i] == ')' else 0
i += 1
if k != i:
result *= myeval_plus(string, k, i)
return result
with open("input.txt") as file:
print(sum(
myeval_multiply(line, 0, len(line)) for line in (line.strip().replace(' ', '') for line in file)
))