@@ -162,8 +162,7 @@ def selection(
162162 True
163163 """
164164 contenders = random .sample (list (zip (population , fitnesses )), tournament_k )
165- get_fitness = lambda contender : contender [1 ]
166- return max (contenders , key = get_fitness )[0 ][:]
165+ return max (contenders , key = lambda contender : contender [1 ])[0 ][:]
167166
168167
169168def crossover (
@@ -258,8 +257,6 @@ def run_ga(
258257 ... p_crossover=0.9, p_mutation=0.05,
259258 ... tournament_k=2, elitism=1
260259 ... )
261- >>> sorted(out.keys())
262- ['avg_history', 'best_genome', 'best_history', 'best_value', 'best_weight', 'capacity']
263260 >>> len(out['best_history']) == 5 and len(out['avg_history']) == 5
264261 True
265262 >>> isinstance(out['best_genome'], list) and isinstance(out['best_value'], int)
@@ -286,8 +283,8 @@ def run_ga(
286283 best_overall = population [best_idx ][:]
287284
288285 # Elitism
289- get_fitness = lambda idx : fitnesses [idx ]
290- elite_indices = sorted ( range ( pop_size ), key = get_fitness , reverse = True ) [:elitism ]
286+ sorted_indices = sorted ( range ( pop_size ), key = lambda idx : fitnesses [idx ])
287+ elite_indices = sorted_indices . reverse [:elitism ]
291288 elites = [population [idx ][:] for idx in elite_indices ]
292289
293290 # New generation
@@ -317,18 +314,19 @@ def run_ga(
317314
318315if __name__ == "__main__" :
319316 result = run_ga (items , capacity )
320- best_items = [
321- items [idx ] for idx , bit in enumerate (result ["best_genome" ]) if bit == 1
322- ]
317+ best_value , best_weight = result ["best_value" ], result ["best_weight" ]
323318
324319 print (f"Knapsack capacity: { result ['capacity' ]} " )
325320 print (
326- f"Best solution: value = { result [ ' best_value' ] } , weight = { result [ ' best_weight' ] } "
321+ f"Best solution: value = { best_value } , weight = { best_weight } "
327322 )
328- # Uncomment to inspect chosen items:
323+ # # Uncomment to inspect chosen items:
324+ # best_items = [
325+ # items[idx] for idx, bit in enumerate(result["best_genome"]) if bit == 1
326+ # ]
329327 # print("Items included in the best solution:", best_items)
330328
331- # Optional: plot fitness curves
329+ # # Optional: plot fitness curves
332330 # import matplotlib.pyplot as plt
333331 # plt.figure()
334332 # plt.plot(result["best_history"], label="Best fitness")
0 commit comments