Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Chapter5/genetic_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ def __init__(self, initial_population: List[C], threshold: float, max_generation

# Use the probability distribution wheel to pick 2 parents
# Note: will not work with negative fitness results
def _pick_roulette(self, wheel: List[float]) -> Tuple[C, C]:
def _pick_roulette(self, wheel: List[float]) -> Tuple[C, ...]:
return tuple(choices(self._population, weights=wheel, k=2))

# Choose num_participants at random and take the best 2
def _pick_tournament(self, num_participants: int) -> Tuple[C, C]:
def _pick_tournament(self, num_participants: int) -> Tuple[C, ...]:
participants: List[C] = choices(self._population, k=num_participants)
return tuple(nlargest(2, participants, key=self._fitness_key))

Expand All @@ -53,7 +53,7 @@ def _reproduce_and_replace(self) -> None:
while len(new_population) < len(self._population):
# pick the 2 parents
if self._selection_type == GeneticAlgorithm.SelectionType.ROULETTE:
parents: Tuple[C, C] = self._pick_roulette([x.fitness() for x in self._population])
parents: Tuple[C, ...] = self._pick_roulette([x.fitness() for x in self._population])
else:
parents = self._pick_tournament(len(self._population) // 2)
# potentially crossover the 2 parents
Expand Down