Day 4 - Advent of Code 2022

Working solutions for the day 4 puzzles.

Part One

""" day_04_01.py """

# usage: python3 day_04_01.py < input

import sys


def expand(sections):
    """ calculate set of sections from compact form """
    begin, end = sections.split('-')
    return set(range(int(begin), int(end) + 1))


def subset(pair):
    """ calculate if one of the pair is a subset of the other """
    one, two = list(map(expand, pair.strip().split(',')))
    return one <= two or two <= one


with sys.stdin as pipe:
    subsets = [1 for line in pipe if subset(line)]
print(sum(subsets))

Part Two

""" day_04_02.py """

# usage: python3 day_04_02.py < input

import sys


def expand(sections):
    """ calculate set of sections from compact form """
    begin, end = sections.split('-')
    return set(range(int(begin), int(end) + 1))


def overlap(pair):
    """ calculate if the pair overlap """
    one, two = list(map(expand, pair.strip().split(',')))
    return bool(one & two)


with sys.stdin as pipe:
    overlaps = [1 for line in pipe if overlap(line)]
print(sum(overlaps))