A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/xavdid/advent-of-code-python-template below:

xavdid/advent-of-code-python-template: This is my tried-and-true Python helper for solving Advent of Code puzzles

@xavdid's Python Advent of Code Project Template

This is my tried-and-true Python utility package for the phenomenal Advent of Code puzzles. It handles creating stub solutions, input parsing, and printing your answer, letting you focus on the actual solve. I've been using it since 2017. It doesn't do too much though- it doesn't pull or submit your input automatically, so no auth is required.

Additionally, Over in the main repo, I include a step-by-step explanation of each puzzle if you're in the learning mood!

To use this base class for your own solutions:

  1. Ensure you have Python 3.12 or higher. You can use mise or pyenv to manage your Python versions. It may work on older versions, but 3.12-specific features will be added without further breaking changes
  2. Create a new repo using this template (docs) and clone it locally
  3. Start a new solution using ./start
  4. Edit the newly created file at solutions/YEAR/day_01/solution.py
  5. Run your code answers using ./advent
  6. Repeat and enjoy!

This repo has two main commands: start and advent.

./start [-h] [--year YEAR] [day]

Scaffold files to start a new Advent of Code solution

positional arguments:

optional arguments:

./advent [--year year] [--test-data] [--debug] [--profile] [--slow] [--time] [day]

Run a specific day of Advent of Code

informational flags

positional arguments:

optional flags:

solutions/
├── ...
└── 2020/
    ├── day_01/
    │   ├── solution.py
    │   ├── input.txt
    │   ├── input.test.txt
    │   └── README.md
    ├── day_02/
    │   ├── solution.py
    │   ├── ...
    └── ...

Each day_NN folder has the following files:

A helpful base class on which to build your AoC solutions. It's got 2 required properties (which should be pre-filled if you use ./start): _year and _day, corresponding to the puzzle you're solving.

Your puzzle input, the parsed contents of the day's input.txt, will be available at self.input. Learn more in Reading Input.

There's also a convenience method for print-based debugging: self.debug(). You can pass it any number of items and they'll get pretty-printed. It only prints if you use the --debug flag with ./advent.

AoC input takes a number of forms, so there are a number of simple modes for input parsing. Your generated Solution class should inherit from one of the following classes, which will parse self.input for you:

Inherited Class description sample input for this mode StrSplitSolution (the default) str[], split by a specified separator (default newline) a
b
c
d
e TextSolution one solid block of text abcde IntSplitSolution int[], split by a specified separator (default newline) 1
2
3
4
5 IntSolution one number 12345
# input file is "12345"

from ...base import (
    IntSolution,
    IntSplitSolution,
    StrSplitSolution,
    TextSolution,
)

for BaseClass in [TextSolution, IntSolution, StrSplitSolution, IntSplitSolution]:

    class Solution(BaseClass):
        def show_input(self):
            print(f"\n{self.input} (type: {type(self.input)})\n")

    Solution().show_input()

# 12345 (type: <class 'str'>)
# 12345 (type: <class 'int'>)
# ['12345'] (type: <class 'list'>)
# [12345] (type: <class 'list'>)

You can also change the separator to change how the SplitSolutions work:

# input file is "1,2,3,4,5"

from ...base import IntSplitSolution, StrSplitSolution

for BaseClass in [StrSplitSolution, IntSplitSolution]:

    class Solution(BaseClass):
        separator = ","

        def show_input(self):
            print(f"\n{self.input} (type: {type(self.input)})\n")

    Solution().show_input()

# ['1', '2', '3', '4', '5'] (type: <class 'list'>)
# [1, 2, 3, 4, 5] (type: <class 'list'>)

Each AoC puzzle has two parts, so there are two functions you need to write: part_1 and part_2. Each should return an int, since that's typically the answer that AoC expects.

Sometimes, it's easier to calculate both parts in a single function (such as if the answer is asking about two parts of a single computation). In that case, there's also a solve() method, which should return a 2-tuple with your answers (like (5, 7)). solve takes precedence if present. Feel free to delete any unused functions when you're done.

class Solution(TextSolution):
    def part_1(self) -> int:
        return some_computation()

    def part_2(self) -> int:
        return some_other_computation()

    # or:

    def solve(self) -> tuple[int, int]:
        part_1 = 0
        total = 0

        for i in range(10):
            result = some_computation()
            if i == 0:
                part_1 = result

            total += result

        return result

Once you've solved the puzzle, you can decorate your answer function (solve or part_N) with the @answer decorator. It asserts that the value returned from the function is whatever you pass to the decorator:

class Solution(TextSolution):
    _year = 2022
    _day = 5

    @answer(123)
    def part_1(self) -> int:
        return 123

    @answer(234)
    def part_2(self) -> int:
        return 123 # err!

This is helpful for ensuring your answer doesn't change when editing your code after you've solved the puzzle. It's included as a comment in the template. It's ignored when running against test input, so it's easy to verify as you go.

The base class includes a self.debug method which will pretty-print all manner of inputs. These only show up when the --debug flag is used, making it a convenient way to show debugging info selectively.

I recommend the following tools:

If you have both available, then just lint will run them both. I've included a simple ruff configuration file to help get you started.

If you're running many solutions at once and want to exclude individual parts of solutions (or entire days), you can mark individual functions with the @slow decorator. They'll print a warning, but won't actually run the solution.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4