Select the second parent and generate new population >>> random.seed(42) >>> parent_1 = ("123456", 8.0) >>> population_score = [("abcdef", 4.0), ("ghijkl", 5.0), ("mnopqr", 7.0)] >>> genes = list("ABCDEF") >>> child_n = int(min(parent_1[1] + 1, 10)) >>> population = []
(
parent_1: tuple[str, float],
population_score: list[tuple[str, float]],
genes: list[str],
)
| 60 | |
| 61 | # Select, crossover and mutate a new population. |
| 62 | def select( |
| 63 | parent_1: tuple[str, float], |
| 64 | population_score: list[tuple[str, float]], |
| 65 | genes: list[str], |
| 66 | ) -> list[str]: |
| 67 | """ |
| 68 | Select the second parent and generate new population |
| 69 | |
| 70 | >>> random.seed(42) |
| 71 | >>> parent_1 = ("123456", 8.0) |
| 72 | >>> population_score = [("abcdef", 4.0), ("ghijkl", 5.0), ("mnopqr", 7.0)] |
| 73 | >>> genes = list("ABCDEF") |
| 74 | >>> child_n = int(min(parent_1[1] + 1, 10)) |
| 75 | >>> population = [] |
| 76 | >>> for _ in range(child_n): |
| 77 | ... parent_2 = population_score[random.randrange(len(population_score))][0] |
| 78 | ... child_1, child_2 = crossover(parent_1[0], parent_2) |
| 79 | ... population.extend((mutate(child_1, genes), mutate(child_2, genes))) |
| 80 | >>> len(population) == (int(parent_1[1]) + 1) * 2 |
| 81 | True |
| 82 | """ |
| 83 | pop = [] |
| 84 | # Generate more children proportionally to the fitness score. |
| 85 | child_n = int(parent_1[1] * 100) + 1 |
| 86 | child_n = 10 if child_n >= 10 else child_n |
| 87 | for _ in range(child_n): |
| 88 | parent_2 = population_score[random.randint(0, N_SELECTED)][0] |
| 89 | |
| 90 | child_1, child_2 = crossover(parent_1[0], parent_2) |
| 91 | # Append new string to the population list. |
| 92 | pop.append(mutate(child_1, genes)) |
| 93 | pop.append(mutate(child_2, genes)) |
| 94 | return pop |
| 95 | |
| 96 | |
| 97 | def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]: |