Advent of Code 2020: Python Solution Day 18

qviper

Viper

Posted on December 18, 2020

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)
    def __add__(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))
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
qviper
Viper

Posted on December 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advent of Code 2020: Python Solution Day 21
adventofcode Advent of Code 2020: Python Solution Day 21

December 21, 2020

Advent of Code 2020: Python Solution Day 18
adventofcode Advent of Code 2020: Python Solution Day 18

December 18, 2020

Advent of Code 2020: Python Solution Day 10
adventofcode Advent of Code 2020: Python Solution Day 10

December 10, 2020

Advent of Code 2020: Python Solution Day 9
adventofcode Advent of Code 2020: Python Solution Day 9

December 9, 2020