Dazbo's Advent of Code solutions, written in Python
Reading FilesMy AoC TemplateMap
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
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:
list
.str
, containing all the meal calorie values for that elf. Each calorie value is separated by a single newline character. (Because all the calorie values were on separate lines.)str
into its constituent numbers, by using splitlines()
. Each calorie value is returned as a str
.str
to an int
. The Pythonic way to do this is using the map()
function.list
.max()
to return the biggest number in our list.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")
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:
[-3:]
. That means, get all the elements starting with the third from the end (because -1
is the last, -2
is adjacent to the last, and so on), all the way to the last element (inclusive).sum
the slice.So, we just need to add this to our main()
method:
elf_calories = sorted(elf_calories)
print(f"Part 2: {sum(elf_calories[-3:])}")
The output looks like this:
Part 1: 67016
Part 2: 200116
Execution time: 0.0007 seconds