from puzzle1 import * verbose = False def swap(lst, idx_a, idx_b): temp = lst[idx_a] lst[idx_a] = lst[idx_b] lst[idx_b] = temp def fix_update(update, rules): """Fixes update according to rules by reference.""" # Allow the loop to be restared after a fix. i = 0 swap_free = False while not swap_free: swap_free = True for rule in rules: lhs, rhs = rule if not lhs in update or not rhs in update: continue idx_lhs, idx_rhs = update.index(lhs), update.index(rhs) if idx_lhs > idx_rhs: if verbose: print(f"swapping as {lhs} < {rhs}") swap(update, idx_lhs, idx_rhs) swap_free = False if __name__ == "__main__": rules, updates = load_input() middle_sum = 0 # Let's assume numbers can only occur once (although the checker does not # make this assumption), and every update CAN be fixed. for idx, update in enumerate(updates): if verbose: print(f"{idx:5d}/{len(updates)}:", update) if is_update_legal(update, rules): if verbose: print(update, " is legal") else: if verbose: print(update, " is illegal") fix_update(update, rules) middle_sum += middle_page_num(update) print(f"The sum of middle page numbers of legal updates is {middle_sum}.")