Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Last active December 5, 2022 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbueno/1daf1755bd838a9c989d502f4257a727 to your computer and use it in GitHub Desktop.
Save jsbueno/1daf1755bd838a9c989d502f4257a727 to your computer and use it in GitHub Desktop.
Advent of code, dec, 4th 2022, parts 1 and 2
"""
( https://adventofcode.com/2022/day/4 )
SPOILER ALERT! The snippets in here present a complete solution
This is both "my style" and what I like most about Python:
creating a minimal class which implements one or more operators
turns the solving of thiz puzzle into a super-readable
one liner!
### attempt that I solve these in an Ipython interactive session.
### (terminal based) - so I just type in the functions/methods/classes that I need,
### and go storing intermediate results in lists or other structures as I see fit.
### (in this case "aa" for each line of the input as a string, and "bb" as created bellow)
"""
# The class:
class Plift:
def __init__(self, rng):
self.lower, self.upper = map(int, rng.split("-"))
def __contains__(self, other):
return self.lower <= other.lower and self.upper >= other.upper
def __repr__(self):
return f"({self.lower}, {self.upper})"
# one line to parse the input into pairs of "Borg" instances:
bb = [tuple(Plift(part) for part in line.split(",")) for line in aa]
# and one-liner to solve it all:
sum((line[0] in line[1]) or (line[1] in line[0]) for line in bb )
# for part 2, the "counting" criteria changes from finding "included" ranges
# to overlapped ranges. I opted to use the "|" (binary or) operator for that -
# just typed in the new method at the prompt¨:
def __or__(self, other):
return self.lower <= other.upper and self.upper >= other.lower
# and assigned it to the _Existing_ class:
Plift.__or__ = __or__
# instantly, all instances already
# created of "Plift" in the "bb" list now have the capabiity
# of checking for overlapping with the "|" operator
# And now, one line for totalizing part 2:
sum(line[0] | line[1] for line in bb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment