Skip to content

Commit ef5c679

Browse files
Fix type issues
1 parent c27f588 commit ef5c679

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

genetic_algorithm/knapsack.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -265,22 +265,22 @@ def run_ga(
265265
True
266266
"""
267267
population = [random_genome(len(items)) for _ in range(pop_size)]
268-
best_history = [] # track best fitness per generation
269-
avg_history = []
270-
best_overall = None
271-
best_fit_overall = -1
268+
best_fitness_history: list[int] = [] # track best fitness per generation
269+
avg_fitness_history: list[int] = []
270+
best_genome_overall: genome_t = []
271+
best_fitness_overall: int = -1
272272

273273
for _ in range(generations):
274274
fitnesses = [evaluate(genome, items, capacity)[0] for genome in population]
275275
best_fit = max(fitnesses)
276276
best_idx = fitnesses.index(best_fit)
277-
best_history.append(best_fit)
277+
best_fitness_history.append(best_fit)
278278
avg_fit = sum(fitnesses) / pop_size
279-
avg_history.append(avg_fit)
279+
avg_fitness_history.append(avg_fit)
280280

281-
if best_fit > best_fit_overall:
282-
best_fit_overall = best_fit
283-
best_overall = population[best_idx][:]
281+
if best_fit > best_fitness_overall:
282+
best_fitness_overall = best_fit
283+
best_genome_overall = population[best_idx][:]
284284

285285
# Elitism
286286
sorted_indices = sorted(range(pop_size), key=lambda idx: fitnesses[idx])
@@ -299,14 +299,14 @@ def run_ga(
299299
population = new_pop[:pop_size]
300300

301301
# Final evaluation of the best
302-
best_value, best_weight = evaluate(best_overall, items, capacity)
302+
best_value, best_weight = evaluate(best_genome_overall, items, capacity)
303303
return {
304-
"best_genome": best_overall,
304+
"best_genome": best_genome_overall,
305305
"best_value": best_value,
306306
"best_weight": best_weight,
307307
"capacity": capacity,
308-
"best_history": best_history,
309-
"avg_history": avg_history,
308+
"best_fitness_history": best_fitness_history,
309+
"avg_fitness_history": avg_fitness_history,
310310
}
311311

312312

@@ -327,8 +327,8 @@ def run_ga(
327327
# # Optional: plot fitness curves
328328
# import matplotlib.pyplot as plt
329329
# plt.figure()
330-
# plt.plot(result["best_history"], label="Best fitness")
331-
# plt.plot(result["avg_history"], label="Average fitness")
330+
# plt.plot(result["best_fitness_history"], label="Best fitness")
331+
# plt.plot(result["avg_fitness_history"], label="Average fitness")
332332
# plt.title("GA on Knapsack: Fitness over Generations")
333333
# plt.xlabel("Generation")
334334
# plt.ylabel("Fitness")

0 commit comments

Comments
 (0)