advent_of_code_2021

My attempts to work through the 2021 Advent of Code problems.
git clone https://git.eamoncaddigan.net/advent_of_code_2021.git
Log | Files | Refs | README | LICENSE

utils.py (2071B)


      1 """A collection of utilities that should be useful for more than one puzzle."""
      2 
      3 import os.path
      4 from typing import Any, Tuple
      5 import requests
      6 import numpy as np
      7 import pandas as pd
      8 
      9 def convert_input_to_array(input_string: str) -> np.ndarray:
     10     """Convert the (newline-delimited) input string into a 2d int array"""
     11     return (
     12         np.array([list(line) for line in input_string.rstrip('\n').split('\n')])
     13         .astype(int)
     14     )
     15 
     16 def convert_lines_to_series(input_string: str) -> pd.Series:
     17     """Return a pandas Series consisting of the lines in the
     18     (newline-delimited) input string"""
     19     return pd.Series(input_string.rstrip('\n').split('\n'))
     20 
     21 def convert_int_line_to_series(input_string: str) -> pd.Series:
     22     """Converts one (optionally newline-terminated) string of comma-separated
     23     integers to a pandas Series"""
     24     return pd.Series(input_string.rstrip().split(',')).astype(np.int64)
     25 
     26 def wc(input_string: str) -> Tuple[int, int, int]:
     27     """Returns the newline, word, and character counts of the given input
     28     string"""
     29     return (sum([1 for _ in input_string if _ == '\n']),
     30             len(input_string.split()),
     31             len(input_string))
     32 
     33 def get_puzzle_input(day_number: int, binary: bool = False) -> Any:
     34     """Downloads and returns the input data for the puzzle on a given day.
     35     Note: requires a 'session' cookie string to be stored in
     36     '~/.config/advent_of_code/session' and will raise an error if it's not
     37     found. Set `binary` to `True` to receive binary (and not text) data."""
     38     if binary:
     39         raise RuntimeError('binary file output not supported yet')
     40 
     41     with open(os.path.expanduser('~/.config/advent_of_code/session'),
     42               'rt', encoding='utf8') \
     43             as f_in:
     44         session = f_in.readline().strip()
     45 
     46     response = requests.get(f'https://adventofcode.com/2021/day/{day_number}/input',
     47                             cookies={'session': session},
     48                             headers={'User-Aent': 'advent_of_code_2021/0.1'})
     49 
     50     response.raise_for_status()
     51 
     52     return response.text