···11+import fileinput
22+from collections import defaultdict
33+44+from utils import parse_nums
55+66+77+def is_unordered(graph, update):
88+ """Returns -1 if ordered, else the index of the first bad page."""
99+ for i, n in enumerate(update):
1010+ if any(n in graph[m] for m in update[i+1:]):
1111+ return i
1212+1313+ return -1
1414+1515+def mid(lst):
1616+ return lst[(len(lst) - 1) // 2]
1717+1818+1919+on_updates = False
2020+graph = defaultdict(set)
2121+updates = []
2222+for line in fileinput.input():
2323+ if on_updates:
2424+ updates.append(parse_nums(line))
2525+ else:
2626+ if line.strip():
2727+ x, y = parse_nums(line)
2828+ graph[x].add(y)
2929+ else:
3030+ on_updates = True
3131+3232+part_1 = 0
3333+part_2 = 0
3434+3535+for update in updates:
3636+ if is_unordered(graph, update) == -1:
3737+ part_1 += mid(update)
3838+ else:
3939+ while True:
4040+ swap = False
4141+ for i, n in enumerate(update):
4242+ afters = update[i+1:]
4343+ if any(n in graph[a] for a in afters):
4444+ update[i], update[i + 1] = update[i + 1], update[i]
4545+ swap = True
4646+ if not swap:
4747+ break
4848+4949+ part_2 += mid(update)
5050+5151+print("Part 1:", part_1)
5252+print("Part 2:", part_2)