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

commit d05ab6a516b87d46acbb0fcfb9126895620bdc44
parent 343ef4b9d593242cc406725a64e203f5b9a08fe6
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date:   Wed,  1 Dec 2021 04:51:10 -0500

My solution to day 1, part 1

Diffstat:
Aday01_part1.py | 41+++++++++++++++++++++++++++++++++++++++++
Mutils.py | 5++---
2 files changed, 43 insertions(+), 3 deletions(-)

diff --git a/day01_part1.py b/day01_part1.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +"""For Day 1, part 1 of the 2021 Advent of Code, we're simply inspecting a +stream of numbers and counting the number of times that an item in the stream +is greater than the preceding element.""" + +# As I work through these problems, I will often decide whether I want to use a +# pure Python approach, or whether I want to use numpy/scipy. I feel like I +# have more familiarity with the language in general than these libraries, so +# I'm going to lean on them more heavily than might be necessary. For instance, +# I could make a `lag` iterator and `zip` the original stream with its lagged +# version, but I'm not doing that here. + +from io import StringIO +import pandas as pd +from utils import get_puzzle_input + +def download_input_data(): + """Downloads the data for the day and returns a pandas data frame with a + single column named `depth`""" + return pd.read_csv(StringIO(get_puzzle_input(1)), + names=('depth',)) + +def calculate_depth_diffs(depth_series): + """Given a pandas series of depths, returns the difference between each + element and the preceding one""" + return depth_series - depth_series.shift(1) + +def count_depth_increases(depth_diff_series): + """Given a pandas series of depth differences, count the number of + increases""" + return (depth_diff_series > 0).sum() + +if __name__ == "__main__": + """Download the data, find the answer, and print it to the terminal""" + depth_data = download_input_data() + + depth_data['depth_diff'] = calculate_depth_diffs(depth_data['depth']) + + number_of_increases = count_depth_increases(depth_data['depth_diff']) + + print(f'{number_of_increases = }') diff --git a/utils.py b/utils.py @@ -13,10 +13,9 @@ def get_puzzle_input(day_number): session = f_in.readline().strip() response = requests.get(f'https://adventofcode.com/2021/day/{day_number}/input', - cookies = {'session': session}, - headers = {'User-Aent': 'advent_of_code_2021/0.1'}) + cookies={'session': session}, + headers={'User-Aent': 'advent_of_code_2021/0.1'}) response.raise_for_status() return response.text -