Added doc strings to solver.py

master
Tibor Bizjak 2023-03-04 15:20:58 +01:00
parent 5bb33c70e8
commit 22a9ca179a
1 changed files with 27 additions and 0 deletions

View File

@ -11,10 +11,20 @@ PATH = pathlib.Path(__file__).parent
INPUT_PATH = PATH / "input"
class Tests(list):
"""
Test cases class. A test case is a tuple of the form
(puzzle_input, partI_result, partII_result).
"""
def add(self, test_input, partI=None, partII=None):
"""Add a test case"""
self.append((str(test_input), partI, partII))
def testf(tests, f, part):
"""
Tests a function f on test cases tests and compares the result
to test_case[part]. The test is not run if test_case[part] == None.
"""
tests = [(t[0], t[part]) for t in tests if t[part] != None]
if tests == []:
return "No tests"
@ -30,8 +40,16 @@ def testf(tests, f, part):
class Solver:
"""
Solver class. A solver is a module with functions partI and partII,
an optional preprocessing function preproc, and an optional variable
tests of type Tests.
"""
def __init__(self, mod):
"""Initilizes the solver instance of module mod."""
def unpack(name, default):
"""Returns mod.name if it exists and default otherwise."""
return getattr(mod, name) if name in dir(mod) else default
dn_pattern = re.compile("\d\d?")
@ -41,6 +59,11 @@ class Solver:
self.partII = getattr(mod, 'partII')
def format_result(f):
"""
Formatting decorator. Formats and prints a tuple representing
the results of partI and partII.
"""
def aux(*args):
solver = args[0]
ptI, ptII = f(*args)
@ -50,6 +73,7 @@ class Solver:
@format_result
def solve(self, puzzle_input):
"""Solves puzzle input and prints the results."""
puzzle_input = puzzle_input.rstrip()
if self.preproc != NotImplemented:
puzzle_input = self.preproc(puzzle_input)
@ -59,6 +83,7 @@ class Solver:
@format_result
def test(self):
"""Tests the solver and prints the results."""
tests = self.tests
if self.preproc != NotImplemented:
tests = [(self.preproc(str(t)), s1, s2)
@ -70,6 +95,7 @@ class Solver:
def read_input(mod_name):
"""Reads input of module with mod_name."""
name = mod_name + ".txt"
with open(INPUT_PATH / name) as f:
r = f.read()
@ -93,6 +119,7 @@ parser.add_argument('-t', '--test',
help="run tests")
def parse_day_arg(s):
"""Parses day argument. Returns a list of days."""
split = s.split('-')
if len(split) == 1:
return [int(split[0])]