Learning Python with Advent of Code Walkthroughs

Dazbo's Advent of Code solutions, written in Python

Counting Calories

Advent of Code 2022 - Day 1

Day 1: Calorie Counting

Useful Links

Concepts and Packages Demonstrated

Reading FilesMy AoC TemplateMap

Problem Intro

As usual AoC starts with an easy challenge. This one took me about a minute to write. But if you’re new to AoC, or to Python, don’t sweat it! My first ever Day 1 - when I was learning Python - took me about 30 minutes!

Check out my Python Journey pages to read more about the concepts and modules I use in these solutions.

For this challenge, we’re told that the elves are on an expedition. Each elf is carrying a number of meals, and each meal contains a specific number of calories. This is our input data. Specifically:

So the input data looks something like this:

1000
2000
3000

4000

5000
6000

7000
8000
9000

10000

Part 1

Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?

Okay, so what we need to do is find the block of numbers that adds up to the largest value.

Here’s how I did it:

Here is the code:

from pathlib import Path
import time

SCRIPT_DIR = Path(__file__).parent
# INPUT_FILE = Path(SCRIPT_DIR, "input/sample_input.txt")
INPUT_FILE = Path(SCRIPT_DIR, "input/input.txt")

def main():
    with open(INPUT_FILE, mode="rt") as f:
        elf_meals = f.read().split("\n\n") # split on empty lines
    
    elf_calories = [] # store total calories for each elf
    for elf in elf_meals:
        calories = sum(map(int, elf.splitlines()))
        elf_calories.append(calories)
        
    print(f"Part 1: {max(elf_calories)}")

if __name__ == "__main__":
    t1 = time.perf_counter()
    main()
    t2 = time.perf_counter()
    print(f"Execution time: {t2 - t1:0.4f} seconds")

Part 2

Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?

This is easy to do. My solution:

So, we just need to add this to our main() method:

    elf_calories = sorted(elf_calories)
    print(f"Part 2: {sum(elf_calories[-3:])}")

Results

The output looks like this:

Part 1: 67016
Part 2: 200116
Execution time: 0.0007 seconds