Last active
December 18, 2020 08:02
-
-
Save etotheipi/7c9c3ecc0255c8046b7af3185cd877ae to your computer and use it in GitHub Desktop.
Abusing Python to solve AoC 2020, Day 18 part 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ModInt: | |
""" An int that adds when you * and multiplies when you + """ | |
def __init__(self, val): | |
self.val = val | |
def __mul__(self, other): | |
return ModInt(self.val + other.val) | |
def __add__(self, other): | |
return ModInt(self.val * other.val) | |
accum = 0 | |
for expr in input_lines: | |
ecopy = expr[:] | |
# Replace all int literals in string with new class | |
for c in '0123456789': | |
ecopy = ecopy.replace(c, f'ModInt({c})') | |
# Swap all +/* | |
ecopy = ecopy.replace('*', 'X') | |
ecopy = ecopy.replace('+', '*') | |
ecopy = ecopy.replace('X', '+') | |
# "6*2+(2+(7*7))" has become "ModInt(6)+ModInt(2)*(ModInt(2)*(ModInt(7)+ModInt(7)))" | |
# Built-in eval() applies correct operator precedence | |
accum += eval(ecopy).val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment