This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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