Logo

DaVinci Python AoC22 Solution No. 3

#Solution

# Create a function to calculate the sum of the priorities 
def calc_priority_sum(input):
    # Initialize the priority sum variable
    priority_sum = 0
    
    # Iterate over each rucksack in the input list
    for rucksack in input:
        # Initialize a set to store the item types
        item_types = set()
        
        # Iterate over the items in the rucksack
        for item in rucksack:
            # If the item is lowercase, add its priority to the item_types set
            if item.islower():
                item_types.add(ord(item)-96)
            # If the item is uppercase, add its priority to the item_types set
            else:
                item_types.add(ord(item)-64+26)
        # Check if only one item type appears in both compartments of the rucksack
        if len(item_types) == 1:
            # Add the priority of the item type to the priority sum
            priority_sum += item_types.pop()
    
    # Return the priority sum
    return priority_sum

# Create a list of rucksacks
rucksacks = [
    'vJrwpWtwJgWrhcsFMMfFFhFp',
    'jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL',
    'PmmdzqPrVvPwwTWBwg',
    'wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn',
    'ttgJtRGJQctTZtZT',
    'CrZsJsPPZsGzwwsLwLmpwMDw'
]

# Call the calc_priority_sum() function and print the result
print(calc_priority_sum(rucksacks))

# Output: 157