from itertools import permutations from collections import defaultdict with open("input") as f: instructions = [n.strip() for n in f.readlines()] POINTS = defaultdict(int) PERSONS = set() for instruction in instructions: person_a, _, sign, points, _, _, _, _, _, _, person_b = instruction.split(" ") person_b = person_b.strip(".") multiplicator = 1 if sign == "gain" else -1 points = int(points) * multiplicator person_a, person_b = sorted([person_a, person_b]) POINTS[(person_a, person_b)] += points PERSONS.add(person_a) PERSONS.add(person_b) print("POINTS", POINTS) print("PERSONS", PERSONS) HIGHEST_POINTS = None SEATING_ORDER = None for seating_plan in permutations(PERSONS, len(PERSONS)): points = 0 seating_plan = list(seating_plan) for person_a, person_b in zip(seating_plan, seating_plan[1:] + seating_plan[:1]): person_a, person_b = sorted([person_a, person_b]) points += POINTS[(person_a, person_b)] if HIGHEST_POINTS is None or HIGHEST_POINTS < points: HIGHEST_POINTS = points SEATING_ORDER = seating_plan print("Best order:", SEATING_ORDER) print(HIGHEST_POINTS)