|
| 1 | +from timeit import default_timer as timer |
| 2 | +from itertools import tee |
| 3 | +from typing import Callable, TypeVar, Any |
| 4 | + |
| 5 | + |
| 6 | +T = TypeVar('T') |
| 7 | + |
| 8 | + |
| 9 | +def default_parse_line(line: str) -> list[str]: |
| 10 | + return line.strip().split() |
| 11 | + |
| 12 | + |
| 13 | +def read_input(fname: str, separator: str = '\n', parse_chunk: Callable[[str], T] = default_parse_line) -> list[T]: |
| 14 | + with open(fname) as f: |
| 15 | + return [parse_chunk(line) for line in f.read().rstrip().split(separator)] |
| 16 | + |
| 17 | + |
| 18 | +def timed(f, *args, **kwargs): |
| 19 | + t1 = timer() |
| 20 | + result = f(*args, **kwargs) |
| 21 | + t2 = timer() |
| 22 | + return result, t2 - t1 |
| 23 | + |
| 24 | + |
| 25 | +def sliding_window(iterable, size): |
| 26 | + iterables = tee(iterable, size) |
| 27 | + for i, iterator in enumerate(iterables): |
| 28 | + for _ in range(i): |
| 29 | + next(iterator) |
| 30 | + return zip(*iterables) |
| 31 | + |
| 32 | + |
| 33 | +def run(part_one, part_two, input_file): |
| 34 | + print("PART 1") |
| 35 | + result, time = timed(part_one, input_file) |
| 36 | + print(f"Answer:\t{result}\nTime:\t{time*1000}ms") |
| 37 | + print() |
| 38 | + print(f"PART 2") |
| 39 | + result, time = timed(part_two, input_file) |
| 40 | + print(f"Answer:\t{result}\nTime:\t{time*1000}ms") |
| 41 | + |
| 42 | + |
| 43 | +def run_test(part, test_input_file, expected, test_name: str = "", exit_on_fail: bool = True): |
| 44 | + result, time = timed(part, test_input_file) |
| 45 | + if result == expected: |
| 46 | + print(f"Passed: {test_name} in {time*1000}ms") |
| 47 | + else: |
| 48 | + print(f"Failed: {test_name or test_input_file}\nExpected {expected}, got {result} in {time*1000}ms") |
| 49 | + if exit_on_fail: |
| 50 | + exit(1) |
0 commit comments