Logo

DaVinci Python AoC22 Solution No. 1

# Answer

# define function to get sum of priorities
def get_priority_sum(input):
  # create an empty dict to store item types and priorities 
  item_types = {}
  
  # loop through each line in the input
  for line in input:
    # get the first half of the line, which is the first compartment
    first_compartment = line[:len(line)//2]
    # get the second half of the line, which is the second compartment
    second_compartment = line[len(line)//2:]
    # loop through each character in the first compartment
    for c in first_compartment:
      # if the character is uppercase, add the priority to the dict
      if c.isupper():
        item_types[c] = ord(c) - ord('A') + 27
      # if the character is lowercase, add the priority to the dict
      elif c.islower():
        item_types[c] = ord(c) - ord('a') + 1
    # loop through each character in the second compartment
    for c in second_compartment:
      # if the character is uppercase, add the priority to the dict
      if c.isupper():
        item_types[c] = ord(c) - ord('A') + 27
      # if the character is lowercase, add the priority to the dict
      elif c.islower():
        item_types[c] = ord(c) - ord('a') + 1
  
  # get the sum of all the priorities
  priority_sum = 0
  for k,v in item_types.items():
    priority_sum += v
  
  # return the sum
  return priority_sum

# test input
input = ["vJrwpWtwJgWrhcsFMMfFFhFp", 
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL", 
"PmmdzqPrVvPwwTWBwg", 
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn", 
"ttgJtRGJQctTZtZT", 
"CrZsJsPPZsGzwwsLwLmpwMDw"]

print(get_priority_sum(input))
# Output: 157