import numpy as np # Objective function (the function we want to minimize) def objective(x): return x**2 # simple parabola, minimum is at x = 0 # Lévy flight function (random step generator) def levy_flight(Lambda): u = np.random.normal(0, 1) v = np.random.normal(0, 1) step = u / abs(v)**(1/Lambda) return step # Basic Cuckoo Search def cuckoo_search(n=10, max_iter=50, pa=0.25): nests = np.random.uniform(-10, 10, n) # random initial nests fitness = objective(nests) for t in range(max_iter): for i in range(n): new_nest = nests[i] + levy_flight(1.5) # new solution via Lévy flight new_fit = objective(new_nest) if new_fit < fitness[i]: # if better, replace nests[i] = new_nest fitness[i] = new_fit # Discovery and random replacement (like host birds rejecting eggs) rand_idx = np.random.rand(n) > pa nests[rand_idx] = np.random.uniform(-10, 10, np.sum(rand_idx)) fitness[rand_idx] = objective(nests[rand_idx]) best_nest = nests[np.argmin(fitness)] best_value = np.min(fitness) return best_nest, best_value # Run it best, value = cuckoo_search() print(f"Best solution: x = {best:.4f}, f(x) = {value:.4f}")