from typing import Counter def q1(text: str): l1 = [] l2 = [] for line in text.splitlines(): left, right = list(map(int, line.replace(" ", " ").split())) l1.append(left) l2.append(right) l1.sort() l2.sort() return sum(abs(left-right) for left, right in zip(l1, l2)) def q2(text: str): l1 = [] l2 = Counter() for line in text.splitlines(): left, right = list(map(int, line.replace(" ", " ").split())) l1.append(left) l2[right] += 1 return sum(left * l2[left] for left in l1) if __name__ == "__main__": with open("i1.txt") as f: print(q1(f.read())) with open("i1.txt") as f: print(q2(f.read()))