Skip to content

Instantly share code, notes, and snippets.

@DavidBuchanan314
Created December 3, 2022 12:14
Embed
What would you like to do?
# Open the input file
with open("input.txt") as file:
# Read the contents of the file
data = file.read()
# Split the input on blank lines
elf_data = data.split("\n\n")
# Parse the data for each Elf
elf_calories = []
for elf in elf_data:
# Split each group of lines on newlines
items = elf.split("\n")
# Remove empty lines
items = [x for x in items if x]
# Convert the strings to numbers and sum the Calories
total_calories = 0
for item in items:
try:
# Try to convert the string to a number
calories = int(item)
# If successful, add the calories to the total
total_calories += calories
except ValueError:
# If the string is not a valid number, skip it
continue
# Store the total number of Calories for this Elf
elf_calories.append(total_calories)
# Find the Elf carrying the most Calories
max_calories = max(elf_calories)
# Print the result
print(max_calories)
# Open the input file
with open("input.txt") as file:
# Read the contents of the file
data = file.read()
# Split the input on blank lines
elf_data = data.split("\n\n")
# Parse the data for each Elf
elf_calories = []
for elf in elf_data:
# Split each group of lines on newlines
items = elf.split("\n")
# Remove empty lines
items = [x for x in items if x]
# Convert the strings to numbers and sum the Calories
total_calories = 0
for item in items:
try:
# Try to convert the string to a number
calories = int(item)
# If successful, add the calories to the total
total_calories += calories
except ValueError:
# If the string is not a valid number, skip it
continue
# Store the total number of Calories for this Elf
elf_calories.append(total_calories)
# Sort the Elves by the number of Calories they are carrying
# in descending order
elf_calories.sort(reverse=True)
# Take the top three Elves
top_elves = elf_calories[:3]
# Sum the Calories carried by the top Elves
total_calories = sum(top_elves)
# Print the result
print(total_calories)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment