AoC: Day 04


The Problem

We’re given a bunch of data in key:value pairs that we have to count (part 1) and validate (part 2). If it walks like a dict and talks like a dict…

My Solution

I was consciously looking for opportunities to do a bit of comprehension, so figured out how to do just that. The first had a bit of ugly code for the checks, I implemented the checks for the second part in a big function. Didn’t take me much time and my code ran the first time around, so I was quite happy.

Unfortunately, for the input processing as well as the checks, I directly did what the problem asked, while there were better and more elegant ways of solving the problem…

Implementation

  • Python has a function all that checks if all the entries of a list are true. Cool!
  • Processing the input — I broke the entries when I encountered an empty line. Much better to just split on nn, then join what remains and split on spaces, which gives us all the k:v pairs. Lesson: take a step back and think about the task at hand; the obvious solution isn’t the only one!
  • Comprehensions: the above can be put into a list comprehension, followed by a call to all[[y.split(':') for y in re.split(' |n',x)] for x in r.split('nn')]
  • The biggest learning from this problem: we can use functions as values in a dict (and therefore lambdas as well)! I had no idea this was present, but in retrospect, obvious, as everything in python is an object
, ,

Leave a Reply

Your email address will not be published.