from itertools import islice def _load(filename): with open(filename) as f: for l in f: yield l.rstrip() def load(filename): f = list(_load(filename)) for j in range(0, int(len(f) / 3)): i = j*3 yield f[i], f[i+1], f[i+2] def overlap(c1, c2, c3): return list(set(c1).intersection(set(c2)).intersection(set(c3)))[0] def priority(c): n = ord(c) if ord("a") <= n <= ord("z"): return n - ord("a") + 1 if ord("A") <= n <= ord("Z"): return n - ord("A") + 27 raise Exception() def calcsum(l): l = [overlap(*x) for x in l] t = sum([priority(*x) for x in l]) return t assert priority("a") == 1 assert priority("z") == 26 assert priority("A") == 27 assert priority("Z") == 52 l = list(load("demo.txt")) assert l[0] == ("vJrwpWtwJgWrhcsFMMfFFhFp", "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL", "PmmdzqPrVvPwwTWBwg") assert l[1] == ("wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn", "ttgJtRGJQctTZtZT", "CrZsJsPPZsGzwwsLwLmpwMDw") assert overlap(*l[0]) == "r" assert overlap(*l[1]) == "Z" assert calcsum(l) == 70 l = list(load("data.txt")) print("Sum is:", calcsum(l))