I am engaged on a perform that takes in a NumPy array containing solely mutually distinct constructive sq. numbers. I need the perform to choose a component at random, discover if there’s a decrease constructive sq. quantity than the quantity chosen: (1) if there’s, return the array with the decrease constructive sq. quantity rather than the unique aspect (2) if there is not, return a duplicate of the unique array.
The rationale I am creating this perform is to create a simulated annealing resolution to the Magic Sq. of Squares Puzzle, and this perform would function one of many mutations to the candidate resolution.
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 perform at all times have the behaviour I’ve specified?