import sys from collections import defaultdict as dd from functools import cmp_to_key as ck # load rules R = dd(list) L = open("orders","rt").read().strip().split("\n") for l in L: [a,b] = l.split("|") R[int(a)].append(int(b)) def order(a,b): if a in R: for i in R[a]: if (i==b): return -1 return 1 S = 0 # load incorrect lines I = open("input2","rt").read().strip().split("\n") for l in I: # sort line l = map(int,l.split(",")) l = sorted(l, key=ck(order)) # take middle S += l[(len(l)+1)//2 -1] print(S)