Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 4, 2022 14:28
Embed
What would you like to do?
import sys
total = 0
# Read the input file from the command line arguments
with open(sys.argv[1], "r") as f:
# Initialize a list to store the lines in groups of three
group = []
# Read each line of the input file
for line in f:
# Add the line to the current group
group.append(line)
# If the group has three lines, process it
if len(group) == 3:
# Split each rucksack into its three compartments
compartments = [line[i:i+len(line)//3] for i in range(0, len(line), len(line)//3)]
# Iterate through each character in the first compartment of the first rucksack
for ch in compartments[0]:
# If the character also appears in the other compartments,
# add its priority to the running total
if all(ch in comp for comp in compartments[1:]):
# Lowercase item types have priorities 1 through 26
if ch.islower():
total += ord(ch) - ord("a") + 1
# Uppercase item types have priorities 27 through 52
elif ch.isupper():
total += ord(ch) - ord("A") + 27
# Clear the group
group = []
# Print the sum of the priorities of the item types that correspond to the badges
# of each group
print(total)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment