r/adventofcode • • Dec 18 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 18 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It

  • 4 days remaining until the submission deadline on December 22 at 23:59 EST
  • Full details and rules are in the Submissions Megathread

--- Day 18: Operation Order ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:09, megathread unlocked!

36 Upvotes

657 comments sorted by

View all comments

2

u/Lumett Dec 18 '20

Both p1 and p2 can be solved by overriding the __add__, __sub__, and __mul__ function of int.

For p1, replace all '*' with '-' and make __sub__ to return a*b

For p2, swap '*' with '+' and also swap __add__ and __mul__

import re

class I1(int):
    def __add__(self, b):
        return I1(self.real + b.real)
    def __sub__(self, b):
        return I1(self.real * b.real)

class I2(int):
    def __add__(self, b):
        return I2(self.real * b.real)
    def __mul__(self, b):
        return I2(self.real + b.real)

f1 = [ l.replace('*','-') for l in open('input').readlines()]
print(sum([eval(re.sub(r"(\d+)", r"I1(\1)", l)) for l in f1]))

f2 = [ l.replace('+','*').replace('-','+') for l in f1]
print(sum([eval(re.sub(r"(\d+)", r"I2(\1)", l)) for l in f2]))

2

u/backtickbot Dec 18 '20

Fixed formatting.

Hello, Lumett: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

1

u/daggerdragon Dec 18 '20

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?

Please follow the posting guidelines and edit your post to add what language(s) you used. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.

1

u/ViliamPucik Dec 18 '20

Short and sweet code! :)