this post was submitted on 01 Dec 2023
37 points (91.1% liked)

Advent Of Code

770 readers
75 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Welcome everyone to the 2023 advent of code! Thank you all for stopping by and participating in it in programming.dev whether youre new to the event or doing it again.

This is an unofficial community for the event as no official spot exists on lemmy but ill be running it as best I can with Sigmatics modding as well. Ill be running a solution megathread every day where you can share solutions with other participants to compare your answers and to see the things other people come up with


Day 1: Trebuchet?!


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)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


πŸ”’This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

πŸ”“ Edit: Post has been unlocked after 6 minutes

you are viewing a single comment's thread
view the rest of the comments
[–] b_van_b@programming.dev 2 points 1 year ago

Python 3

I'm trying to practice writing clear, commented, testable functions, so I added some things that are strictly unnecessary for the challenge (docstrings, error raising, type hints, tests...), but I think it's a necessary exercise for me. If anyone has comments or criticism about my attempt at "best practices," please let me know!

Also, I thought it was odd that the correct answer to part 2 requires that you allow for overlapping letters such as "threeight", but that doesn't occur in the sample input. I imagine that many people will hit a wall wondering why their answer is rejected.

day01.py

import re
from pathlib import Path


DIGITS = [
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    r"\d",
]

PATTERN_PART_1 = r"\d"
PATTERN_PART_2 = f"(?=({'|'.join(DIGITS)}))"


def get_digit(s: str) -> int:
    """Return the digit in the input

    Args:
        s (str): one string containing a single digit represented by a single arabic numeral or spelled out in lower-case English

    Returns:
        int: the digit as an integer value
    """

    try:
        return int(s)
    except ValueError:
        return DIGITS.index(s)


def calibration_value(line: str, pattern: str) -> int:
    """Return the calibration value in the input

    Args:
        line (str): one line containing a calibration value
        pattern (str): the regular expression pattern to match

    Raises:
        ValueError: if no digits are found in the line

    Returns:
        int: the calibration value
    """

    digits = re.findall(pattern, line)

    if digits:
        return get_digit(digits[0]) * 10 + get_digit(digits[-1])

    raise ValueError(f"No digits found in: '{line}'")


def calibration_sum(lines: str, pattern: str) -> int:
    """Return the sum of the calibration values in the input

    Args:
        lines (str): one or more lines containing calibration values

    Returns:
        int: the sum of the calibration values
    """

    sum = 0

    for line in lines.split("\n"):
        sum += calibration_value(line, pattern)

    return sum


if __name__ == "__main__":
    path = Path(__file__).resolve().parent / "input" / "day01.txt"

    lines = path.read_text().strip()

    print("Sum of calibration values:")
    print(f"β€’ Part 1: {calibration_sum(lines, PATTERN_PART_1)}")
    print(f"β€’ Part 2: {calibration_sum(lines, PATTERN_PART_2)}")

test_day01.py

import pytest
from advent_2023_python.day01 import (
    calibration_value,
    calibration_sum,
    PATTERN_PART_1,
    PATTERN_PART_2,
)


LINES_PART_1 = [
    ("1abc2", 12),
    ("pqr3stu8vwx", 38),
    ("a1b2c3d4e5f", 15),
    ("treb7uchet", 77),
]
BLOCK_PART_1 = (
    "\n".join([line[0] for line in LINES_PART_1]),
    sum(line[1] for line in LINES_PART_1),
)

LINES_PART_2 = [
    ("two1nine", 29),
    ("eightwothree", 83),
    ("abcone2threexyz", 13),
    ("xtwone3four", 24),
    ("4nineeightseven2", 42),
    ("zoneight234", 14),
    ("7pqrstsixteen", 76),
]
BLOCK_PART_2 = (
    "\n".join([line[0] for line in LINES_PART_2]),
    sum(line[1] for line in LINES_PART_2),
)


def test_part_1():
    for line in LINES_PART_1:
        assert calibration_value(line[0], PATTERN_PART_1) == line[1]

    assert calibration_sum(BLOCK_PART_1[0], PATTERN_PART_1) == BLOCK_PART_1[1]


def test_part_2_with_part_1_values():
    for line in LINES_PART_1:
        assert calibration_value(line[0], PATTERN_PART_2) == line[1]

    assert calibration_sum(BLOCK_PART_1[0], PATTERN_PART_2) == BLOCK_PART_1[1]


def test_part_2_with_part_2_values():
    for line in LINES_PART_2:
        assert calibration_value(line[0], PATTERN_PART_2) == line[1]

    assert calibration_sum(BLOCK_PART_2[0], PATTERN_PART_2) == BLOCK_PART_2[1]


def test_no_digits():
    with pytest.raises(ValueError):
        calibration_value("abc", PATTERN_PART_1)

    with pytest.raises(ValueError):
        calibration_value("abc", PATTERN_PART_2)