aoc/2020/18/18.py
2020-12-18 01:57:51 -06:00

64 lines
1.7 KiB
Python

def read_file():
with open("input.txt","r") as f:
return f.read().split('\n')
import re
def compute(problem):
"""Add and multiply at the same precedence."""
problem = problem.replace(" ","")
# handle parens
if s := re.search(r'(\((\d+)(([+*])(\d+))+\))',problem):
expr = s.groups()[0]
recurser = str(compute(s.groups()[0][1:-1]))
problem = problem.replace(expr, recurser, 1)
return compute(problem)
# handle ops
if s := re.match(r"(\d+)([+*])(\d+)", problem):
a, op, b = s.groups()
expr = s.group()
reducer = str(
int(a) + int(b)
if op == "+"
else int(a) * int(b)
)
problem = problem.replace(expr, reducer, 1)
return compute(problem)
return int(problem)
def compute2(problem):
"""Add, then multiply."""
problem = problem.replace(" ","")
# handle parens
if s := re.search(r'(\((\d+)(([+*])(\d+))+\))',problem):
expr = s.groups()[0]
recurser = str(compute2(s.groups()[0][1:-1]))
problem = problem.replace(expr, recurser, 1)
return compute2(problem)
# handle add
if s := re.search(r"(\d+)\+(\d+)", problem):
expr = s.group()
print(s.groups()[1])
reducer = str(int(s.groups()[0]) + int(s.groups()[1]))
problem = problem.replace(expr, reducer, 1)
return compute2(problem)
# handle multiply
if s := re.match(r"(\d+)\*(\d+)", problem):
expr = s.group()
reducer = str(int(s.groups()[0]) * int(s.groups()[1]))
problem = problem.replace(expr, reducer, 1)
return compute2(problem)
return int(problem)
def part1(problems):
return sum([compute(problem) for problem in problems])
def part2(problems):
return sum([compute2(problem) for problem in problems])
def main():
problems = read_file()
print(part1(problems), part2(problems))
if __name__ == "__main__":
main()