Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 4, 2022 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnyman/61a3c0bd5f3bf152aecfaded110f65e6 to your computer and use it in GitHub Desktop.
Save gnyman/61a3c0bd5f3bf152aecfaded110f65e6 to your computer and use it in GitHub Desktop.
import sys
total = 0
# Read the input file from the command line arguments
with open(sys.argv[1], "r") as f:
# Read each line of the input file
for line in f:
# Keep track of the characters that have already been counted
# for the current rucksack
counted = set()
# Split the line into two compartments
comp1, comp2 = line[:len(line)//2], line[len(line)//2:]
# Iterate through each character in the first compartment
for ch in comp1:
# If the character also appears in the second compartment,
# and it hasn't been counted already, add its priority to the
# running total
if ch in comp2 and ch not in counted:
counted.add(ch)
# 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
# Print the sum of the priorities of the item types that appear in both
# compartments of each rucksack
print(total)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment