input_square = [[int(value) for value in input().strip().split()] for i in range(3)] magic_squares = [ [[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]], [[2, 7, 6], [9, 5, 1], [4, 3, 8]] ] def cost(initial_square, other_square): """ Calculate the cost to move from ``initial_square`` to ``other_square`` by changing digits a to b where the cost of the operation is |a - b| Args: initial_square (list): a 2 dimensional list other_square (list): a 2 dimensional list of same dimensions as ``initial_square`` """ cost = 0 for initial_column, other_column in zip(initial_square, other_square): for initial_value, other_value in zip(initial_column, other_column): cost += abs(initial_value - other_value) return cost def lowest_cost(square, other_squares): """ Find the lowest cost to move from ``square`` to any of ``other_squares`` by changing digits a to b where the cost of the operation is |a - b| Args: initial_square (list): a 2 dimensional list other_squares (list): a list of 2 dimensional lists, each with the same dimensions as ``initial_square`` """ return min((cost(square, other) for other in other_squares)) print(lowest_cost(input_square, magic_squares))