Day 4 - Advent of Code 2026

Working solutions for the day 4 puzzles.

Part One

""" day_04_01.py """

# usage: python3 day_04_01.py < input

import sys


def valid(values):
    """ are values consistent with each other """
    vs = list(set(values))
    if len(vs) == 1:
        return True

    stub = vs[0]
    for v in vs[1:]:
        temp = ''
        for i, j in zip(stub, v):
            if j in (i, '?'):
                temp += i
            elif i == '?':
                temp += j
            else:
                return False
        stub = temp

    return True


def instructions(text):
    """ instructions for printer """
    size = len(text)
    for period in range(1, size + 1):
        padded = text + (size - size % period) * '?'
        cases = [padded[i:i + period]
                 for i in range(0, size + 1, period)]
        if valid(cases):
            return period

    return None


with sys.stdin as infile:
    total = 0
    while (barcode := infile.readline().strip()):
        total += instructions(barcode)

print(total)

Part Two

""" day_04_02.py """

# usage: python3 day_04_02.py < input

import sys


def valid(values):
    """ are values consistent with each other """
    vs = list(set(values))
    if len(vs) == 1:
        return True

    stub = vs[0]
    for v in vs[1:]:
        temp = ''
        for i, j in zip(stub, v):
            if j in (i, '?'):
                temp += i
            elif i == '?':
                temp += j
            else:
                return False
        stub = temp

    return True


def instructions(text):
    """ instructions for printer """
    size = len(text)
    for period in range(1, size + 1):
        padded = text + (size - size % period) * '?'
        cases = [padded[i:i + period]
                 for i in range(0, size + 1, period)]
        if valid(cases):
            return period

    return None


with sys.stdin as infile:
    barcode = ''.join(infile.read().splitlines())

total = instructions(barcode)

print(total)