aoc2020/18/2.py

32 lines
811 B
Python
Raw Normal View History

2020-12-18 11:14:06 +01:00
with open("input") as f:
content = [x.strip().replace(")", " )").replace("(", "( ").split(" ") for x in f]
def evaluate(expression, startpos):
2020-12-18 11:20:38 +01:00
sumresult = 0
2020-12-18 11:14:06 +01:00
number = 0
i = startpos
2020-12-18 11:20:38 +01:00
endpos = None
mulresult = 1
2020-12-18 11:14:06 +01:00
while i < len(expression):
number = None
if expression[i] == "(":
number, i = evaluate(expression, i + 1)
elif expression[i] == ")":
endpos = i
break
elif expression[i] == "*":
2020-12-18 11:20:38 +01:00
mulresult *= sumresult
sumresult = 0
2020-12-18 11:14:06 +01:00
elif expression[i] != "+":
number = int(expression[i])
if number is not None:
2020-12-18 11:20:38 +01:00
sumresult += number
2020-12-18 11:14:06 +01:00
i += 1
2020-12-18 11:20:38 +01:00
mulresult *= sumresult
2020-12-18 11:14:06 +01:00
2020-12-18 11:20:38 +01:00
return mulresult, endpos
2020-12-18 11:14:06 +01:00
print(sum(map(lambda x: evaluate(x, 0)[0], content)))