Representation Design Output def initpopulation(): populations = [] for i in…
- User
Representation Design Output
def init_population(): populations = [] for i in range(config["population_size"]): x1 = random.uniform(*config["x1_bounds"]) x2 = random.uniform(*config["x2_bounds"]) chromosome = [x1, x2] populations.append(chromosome) print(f"Individual {i+1}: {chromosome}") return populations
Page 13 of the main book
min f(x) <==> max[—f(x)]
max f(x) <==> min[-f(x)]
def fitness(populations): fitness_values = [] # for i, chromosome in enumerate(populations) for i, chromosome in enumerate(populations): x1 = chromosome[0] x2 = chromosome[1] beale_val = beale(x1, x2) fitness = -beale_val fitness_values.append(fitness) print(f"Individual {i+1} Fitness Value : {fitness}") return fitness_values
those function are pretty similar. how do we make it so we not doing dry(don't repeat yourself)
- Assistant
You can refactor the code by creating a helper function to print the individual's information, and reuse it in both the init_population and fitness functions. Here's an example:
def init_population(): populations = [] for i in range(config["population_size"]): x1 = random.uniform(*config["x1_bounds"]) x2 = random.uniform(*config["x2_bounds"]) chromosome = [x1, x2] populations.append(chromosome) print_individual_info(i, chromosome, "Individual") return populations def fitness(populations): fitness_values = [] for i, chromosome in enumerate(populations): x1 = chromosome[0] x2 = chromosome[1] beale_val = beale(x1, x2) fitness = -beale_val fitness_values.append(fitness) print_individual_info(i, fitness, "Individual Fitness Value") return fitness_values def print_individual_info(i, value, label): print(f"{label} {i+1}: {value}")This way, you avoid repeating the print statement and make the code more readable.