#!/usr/bin/env python3 from functools import cmp_to_key o = {} p = {} i = [] with open("day05") as f: l = f.readline() while l != '\n': a,b = map(int, l.strip().split('|')) if a in o: o[a].add(b) else: o[a] = {b} if b in p: p[b].add(a) else: p[b] = {a} l = f.readline() for l in f: i.append(list(map(int, l.strip().split(',')))) # 1 res = 0 un = [] for l in i: for j in range(len(l)): if l[j] in o: if not set(l[j+1:]) <= o[l[j]]: un.append(l) break if l[j] in p: if not set(l[:j]) <= p[l[j]]: un.append(l) break else: res += l[len(l)//2] # 2 def cmp(a,b): if a in o and b in o[a]: return -1 if b in o and a in o[a]: return 1 else: return 0 res = 0 for l in un: ls = sorted(l, key=cmp_to_key(cmp)) res += ls[len(ls)//2]