aoc2022/3/a.py

43 lines
1.3 KiB
Python

# All items of a given type are meant to go into exactly one of the two compartments.
# The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.
# Every item type is identified by a single lowercase or uppercase letter
# The list of items for each rucksack is given as characters all on a single line.
# A given rucksack always has the same number of items in each of its two compartments,
# so the first half of the characters represent items in the first compartment,
# while the second half of the characters represent items in the second compartment.
from collections import defaultdict
def get_prio(c):
# Lowercase item types a through z have priorities 1 through 26.
# Uppercase item types A through Z have priorities 27 through 52.
c = ord(c)
if c >= 97 and c <= 122:
return c - 96
return c - 38
total = 0
with open("input.txt") as f:
for line in f:
line = line.strip()
print(line)
half = len(line) / 2
charsleft = defaultdict(int)
charsright = defaultdict(int)
for i, c in enumerate(line):
(charsleft if i < half else charsright)[c] += 1
common = set(charsleft.keys()).intersection(set(charsright.keys()))
assert len(common) == 1
total += get_prio(common.pop())
print(total)