I am engaged on a operate that takes in a NumPy array containing solely mutually distinct optimistic sq. numbers. I would like the operate to choose a component at random, discover if there’s a decrease optimistic sq. quantity than the quantity chosen: (1) if there may be, return the array with the decrease optimistic sq. quantity rather than the unique component (2) if there is not, return a replica of the unique array.
The rationale I am creating this operate is to create a simulated annealing answer to the Magic Sq. of Squares Puzzle, and this operate would function one of many mutations to the candidate answer.
I’ve had a go on the implementation:
def last_square(x): xcopy = x.copy() index_1 = np.random.randint(0, x.form), np.random.randint(0, x.form) c = x[index_1]-1 whereas np.sqrt(c) != int(np.sqrt(c)) or c in set(x.flatten()): if c < 2: return xcopy else: c -= 1 x[index_1] = c return x
Will my operate at all times have the behaviour I’ve specified?