#!/usr/bin/env python """ For example, suppose you have the following list of contents from six rucksacks: The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p. The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L. The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P. The fourth rucksack's compartments only share item type v. The fifth rucksack's compartments only share item type t. The sixth rucksack's compartments only share item type s. To help prioritize item rearrangement, every item type can be converted to a priority: Lowercase item types a through z have priorities 1 through 26. Uppercase item types A through Z have priorities 27 through 52. In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157. """ import sys from pathlib import Path import string LETTERS = string.ascii_letters INPUTS_DIR = 'inputs' INPUT_FILE = 'day03.txt' PROJECT_DIR = Path('.') FILE_PATH = PROJECT_DIR / INPUTS_DIR / INPUT_FILE def read_data(file_path): """Read file""" for row in open(file_path): yield row.strip() def sum_result(file_path): group = [] _sum_1 = 0 _sum_2 = 0 for s in read_data(file_path): item = check_error(s) priority = get_priority(item) _sum_1 += priority group.append(s) if len(group) == 3: badge = check_badge(*group) badge_priority = get_priority(badge) _sum_2 += badge_priority group.clear() return _sum_1, _sum_2 def check_error(s): s1, s2 = set(s[:len(s) // 2]), set(s[len(s) // 2: ]) return list(s1.intersection(s2))[0] def check_badge(s1, s2, s3): return list(set(s1).intersection(set(s2)).intersection(set(s3)))[0] def get_priority(l): """ Lowercase item types a through z have priorities 1 through 26. Uppercase item types A through Z have priorities 27 through 52. """ return LETTERS.index(l) + 1 examples = [ 'vJrwpWtwJgWrhcsFMMfFFhFp', 'jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL', 'PmmdzqPrVvPwwTWBwg', 'wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn', 'ttgJtRGJQctTZtZT', 'CrZsJsPPZsGzwwsLwLmpwMDw' ] _sum_1 = 0 _sum_2 = 0 group = [] for s in examples: l = check_error(s) p = get_priority(l) _sum_1 += p group.append(s) if len(group) == 3: b = check_badge(group[0], group[1], group[2]) print(b) p = get_priority(b) _sum_2 += p group.clear() print(_sum_1, _sum_2) if __name__ == '__main__': FILE_PATH = sys.argv[1] if len(sys.argv) > 1 else FILE_PATH print(sum_result(FILE_PATH))