## DEV Community is a community of 605,211 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Advent of Code 2020: Python Solution Day 18

This was not a hard task today. It was something like we studied on our Data Structure and Algorithms course, operating a equation on prefix/postfix order. But I had to take help from here. So credit goes to the author.

``````import re

class Solver(int):
def __mul__(self, inp):
return Solver(int(self) + inp)
return Solver(int(self) + inp)
def __sub__(self, inp):
return Solver(int(self) * inp)

def evaluate1(expression):
expression = re.sub(r"(\d+)", r"Solver(\1)", expression)
expression = expression.replace("*", "-")
return eval(expression, {}, {"Solver": Solver})

def evaluate2(expr):
expr = re.sub(r"(\d+)", r"Solver(\1)", expr)
expr = expr.replace("*", "-")
expr = expr.replace("+", "*")
return eval(expr, {}, {"Solver": Solver})

with open("day18.txt") as fp:
lines = [line.split("\n")[0] for line in fp.readlines()]
print("Part 1:", sum(evaluate1(l) for l in lines))
print("Part 2:", sum(evaluate2(l) for l in lines))
``````

## Discussion (9)

Codemonkey51

I spent like 20 minutes working on it using ply and misread the instructions, accidentally flipping precedence, instead of removing it. So I accidentally solved part 2 doing part 1.

Viper

Can you share it? I tried to solve this using recursion but it was too large to parse everything.

Codemonkey51

I think I may have deleted it, once I found an easier way, the same idea that you used. But I could try to recover it. (I'm not good at ply at all, so it had to run 2 scripts to actually work.). One other solution I tried: I made a "math engine" a while ago, it used PEMDAS, but I never finished the parenthesis parsing in it.

Viper

Awesome. 'Math engine' is it publicly available?

Codemonkey51 • Edited

I think I can pull it up on my github, but it is old code, and it doesn't have the best formatting, and variable naming. But I can see if I link it one sec.

Codemonkey51 • Edited

@qviper I can find it, it's just not on github. I think I could put it up right now though.