Day 18
This commit is contained in:
31
day18/part1.py
Normal file
31
day18/part1.py
Normal file
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
|
||||
lines = (x.strip().replace(" ", "") for x in open("input.txt"))
|
||||
RE_PLUS = re.compile(r"\+")
|
||||
RE_MUL = re.compile(r"\*")
|
||||
RE_NUM = re.compile(r"^\d")
|
||||
RE_PAR = re.compile(r"^\((.*?)\)$")
|
||||
|
||||
def evaluate(line):
|
||||
stack = [0]
|
||||
num = 0
|
||||
op = ['+']
|
||||
for char in line:
|
||||
if char in '+*':
|
||||
stack[-1] = stack[-1]*num if op[-1] == '*' else stack[-1]+num
|
||||
op[-1] = char
|
||||
num = 0
|
||||
elif char == '(':
|
||||
stack.append(0)
|
||||
op.append('+')
|
||||
elif char == ')':
|
||||
stack[-1] = stack[-1]*num if op[-1] == '*' else stack[-1]+num
|
||||
num = stack.pop()
|
||||
op.pop()
|
||||
else:
|
||||
num = num*10 + int(char)
|
||||
stack[-1] = stack[-1]*num if op[-1] == '*' else stack[-1]+num
|
||||
return stack[0]
|
||||
|
||||
print(sum(evaluate(line) for line in lines))
|
||||
Reference in New Issue
Block a user