Advent of Code 2022 day 3
Python solution for Advent of Code 2022 day 3. Pretty happy with this one, with perhaps an exception for the repetition in line 15.
import string
import unittest
import utils
def priority_from_rucksack(rucksack):
split_point = int(len(rucksack) / 2)
common_item = (set(rucksack[0:split_point]) & set(rucksack[split_point:])).pop()
return string.ascii_letters.index(common_item) + 1
def group_priorities(rucksacks):
for i in range(0, len(rucksacks), 3):
group = rucksacks[i : i + 3]
badge = (set(group[0]) & set(group[1]) & set(group[2])).pop()
yield string.ascii_letters.index(badge) + 1
def part_one(rucksacks):
return sum([priority_from_rucksack(rucksack) for rucksack in rucksacks])
def part_two(rucksacks):
return sum([group_priority for group_priority in group_priorities(rucksacks)])
if __name__ == "__main__":
rucksacks = utils.get_raw_input("day_03_input.txt")
print(f"Part one: {part_one(rucksacks)}")
print(f"Part two: {part_two(rucksacks)}")
class TestExamples(unittest.TestCase):
def setUp(self):
self.rucksacks = [
"vJrwpWtwJgWrhcsFMMfFFhFp",
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL",
"PmmdzqPrVvPwwTWBwg",
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn",
"ttgJtRGJQctTZtZT",
"CrZsJsPPZsGzwwsLwLmpwMDw",
]
def test_part_one(self):
self.assertEqual(part_one(self.rucksacks), 157)
def test_part_two(self):
self.assertEqual(part_two(self.rucksacks), 70)