day01_part1.py (1604B)
1 #!/usr/bin/env python 2 """For Day 1, part 1 of the 2021 Advent of Code, we're simply inspecting a 3 stream of numbers and counting the number of times that an item in the stream 4 is greater than the preceding element.""" 5 6 # As I work through these problems, I will often decide whether I want to use a 7 # pure Python approach, or whether I want to use numpy/pandas. I feel like I 8 # have more familiarity with the language in general than these libraries, so 9 # I'm going to lean on them more heavily than might be necessary. For instance, 10 # I could make a `lag` iterator and `zip` the original stream with its lagged 11 # version, but I'm not doing that here. 12 13 from io import StringIO 14 import pandas as pd 15 from utils import get_puzzle_input 16 17 def download_input_data(): 18 """Downloads the data for the day and returns a pandas data frame with a 19 single column named `depth`""" 20 return pd.read_csv(StringIO(get_puzzle_input(1)), 21 names=('depth',)) 22 23 def calculate_depth_diffs(depth_series): 24 """Given a pandas series of depths, returns the difference between each 25 element and the preceding one""" 26 return depth_series - depth_series.shift(1) 27 28 def count_depth_increases(depth_diff_series): 29 """Given a pandas series of depth differences, count the number of 30 increases""" 31 return (depth_diff_series > 0).sum() 32 33 def solve_puzzle(): 34 """Return the numeric solution to the puzzle""" 35 return count_depth_increases( 36 calculate_depth_diffs(download_input_data()['depth']) 37 ) 38 39 if __name__ == "__main__": 40 print("Number of depth increases:", solve_puzzle())