with open("day1/input1.txt") as f:
input = f.read().splitlines()Day1
Part 1
- Read in input file contain list of calories
First 100 lines of input looks like this:
['13399',
'13677',
'11945',
'9861',
'6484',
'4257',
'',
'6616',
'7349',
'7758',
'1591',
'6068',
'9217',
'6924',
'6766',
'',
'10040',
'9088',
'11305',
'5867',
'10766',
'9996',
'11092',
'',
'1320',
'4921',
'2338',
'1351',
'3462',
'5916',
'3124',
'1416',
'3655',
'4886',
'1135',
'5171',
'5020',
'5099',
'4785',
'',
'1702',
'5083',
'3852',
'3361',
'2505',
'3767',
'1069',
'3564',
'3189',
'5950',
'2250',
'2053',
'1639',
'1430',
'4586',
'',
'4135',
'7033',
'4649',
'3126',
'1136',
'1435',
'3825',
'2205',
'1259',
'5473',
'1803',
'6406',
'',
'2466',
'30094',
'',
'3122',
'2983',
'5988',
'4214',
'5278',
'1974',
'7109',
'2419',
'3777',
'8299',
'',
'10191',
'6122',
'7298',
'7855',
'8666',
'4777',
'6833',
'8862',
'',
'6100',
'5332',
'1908',
'2796',
'1818',
'4657',
'1650',
'5560']
- Create a generator that returns the totals each time it iterates
generate_totals
generate_totals (input:list[str])
Generate totals from an input string consisting of lines where each line is an integer and delimited by an empty line
| Type | Details | |
|---|---|---|
| input | list | list of strings each containing an int or empty line |
| Returns | typing.Generator[int, NoneType, NoneType] |
sample = ['1','1','','2','3']
pprint(list(generate_totals(sample)))[2, 5]
- Create a function that sums the top n
sum_top_n
sum_top_n (input:list[str], n:int)
Sum top n of totals for the highest n totals
| Type | Details | |
|---|---|---|
| input | list | list of strings each containing an int or empty line |
| n | int | top n count |
- For each sequence of numbers punctuated by an empty line, sum up calories for each
- If sum of calories is greater than current max, set that as the current max
sample = ['1','1','','3','','1','','2','','4','','5']
max_calories = sum_top_n(sample,1)
print(max_calories)5
max_calories = sum_top_n(sample,3)
print(max_calories)12
- Finally the answer for the top 1 given the input
Click on the Answer tab to view the answer
max_calories = sum_top_n(input, 1)
print(f'the correct answer for part 1 is {max_calories}')the correct answer for part 1 is 75622
Part 2
- Part 2 is now easy, since we can handle top
n
Click on the Answer tab to view the answer
max_calories = sum_top_n(input, 3)
print(f'the correct answer for part 2 is {max_calories}')the correct answer for part 2 is 213159