Skip to content

Commit 11273cc

Browse files
Update Genome to genome_t
1 parent 28f2eff commit 11273cc

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

genetic_algorithm/knapsack.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,10 @@ def generate_knapsack_instance(
8787

8888
OVERWEIGHT_PENALTY_FACTOR = 10
8989

90-
Genome = list[int] # An index list where 1 means item is included, 0 means excluded
90+
genome_t = list[int] # An index list where 1 means item is included, 0 means excluded
9191

9292

93-
def evaluate(genome: Genome, items: list[Item], capacity: int) -> tuple[int, int]:
93+
def evaluate(genome: genome_t, items: list[Item], capacity: int) -> tuple[int, int]:
9494
"""
9595
Calculates fitness (value) and weight of a candidate solution. If overweight,
9696
the returned value is penalized; weight is the actual summed weight.
@@ -126,7 +126,7 @@ def evaluate(genome: Genome, items: list[Item], capacity: int) -> tuple[int, int
126126
return total_value, total_weight
127127

128128

129-
def random_genome(n: int) -> Genome:
129+
def random_genome(n: int) -> genome_t:
130130
"""
131131
Generates a random genome (list of 0/1) of length n.
132132
@@ -142,7 +142,7 @@ def random_genome(n: int) -> Genome:
142142
return [random.randint(0, 1) for _ in range(n)]
143143

144144

145-
def selection(population: list[Genome], fitnesses: list[int], k: int) -> Genome:
145+
def selection(population: list[genome_t], fitnesses: list[int], k: int) -> genome_t:
146146
"""
147147
Performs tournament selection to choose a genome from the population.
148148
@@ -164,7 +164,7 @@ def selection(population: list[Genome], fitnesses: list[int], k: int) -> Genome:
164164
return max(contenders, key=get_fitness)[0][:]
165165

166166

167-
def crossover(a: Genome, b: Genome, p_crossover: float) -> tuple[Genome, Genome]:
167+
def crossover(a: genome_t, b: genome_t, p_crossover: float) -> tuple[genome_t, genome_t]:
168168
"""
169169
Performs single-point crossover between two genomes.
170170
If crossover does not occur (random > p_crossover) or genomes are too short,
@@ -197,7 +197,7 @@ def crossover(a: Genome, b: Genome, p_crossover: float) -> tuple[Genome, Genome]
197197
return a[:cutoff_point] + b[cutoff_point:], b[:cutoff_point] + a[cutoff_point:]
198198

199199

200-
def mutation(g: Genome, p_mutation: float) -> Genome:
200+
def mutation(g: genome_t, p_mutation: float) -> genome_t:
201201
"""
202202
Performs bit-flip mutation on a genome. Each bit flips with probability p_mutation.
203203
@@ -232,7 +232,7 @@ def run_ga(
232232
Runs the genetic algorithm to (approximately) solve the knapsack problem.
233233
234234
Returns a dict with keys:
235-
- 'best_genome' (Genome)
235+
- 'best_genome' (genome_t)
236236
- 'best_value' (int)
237237
- 'best_weight' (int)
238238
- 'capacity' (int)

0 commit comments

Comments
 (0)