Day 6: Trash Compactor

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] 2 points 9 months ago

Managed to keep it compact, but boy, do I hate cephalopod math >_<

Python

from csv import reader
from functools import reduce
from itertools import pairwise
from operator import mul
from pathlib import Path
from typing import Any, List, Sequence


def _calc(values: List[str]) -> int:
    match values[-1]:
        case "+":
            return sum(map(int, values[:-1]))
        case "*":
            return reduce(mul, map(int, values[:-1]))
        case _:
            return 0


def _transpose(values: Sequence[Sequence[Any]]) -> List[List[Any]]:
    return [[values[row][col] for row in range(len(values))] for col in range(len(values[0]))]


def part_one(input: str) -> int:
    def _parse_input(input: str) -> List[List[str]]:
        return _transpose(list(map(lambda r: list(filter(None, r)), reader(input.splitlines(), delimiter=" "))))

    return sum(map(_calc, _parse_input(input)))


def part_two(input: str) -> int:
    def _parse_input(input: str) -> List[List[str]]:
        data = list(input.splitlines())
        columns = [t[0] for t in filter(lambda t: t[1] != " ", enumerate(data[-1]))] + [len(data[0])]
        numbers = [[line[a:b] for line in data[:-1]] for a, b in pairwise(columns)]
        numbers = [list(filter(None, ["".join(num).strip() for num in column])) for column in map(_transpose, numbers)]
        return list(map(lambda t: t[0] + [t[1]], zip(numbers, list(filter(None, data[-1].split(" "))))))

    return sum(map(_calc, _parse_input(input)))


if __name__ == "__main__":
    input = Path("_2025/_6/input").read_text("utf-8")
    print(part_one(input))
    print(part_two(input))
  • source