Mutate a random gene of a child with another one from the list. >>> random.seed(123) >>> mutate("123456", list("ABCDEF")) '12345A'
(child: str, genes: list[str])
| 46 | |
| 47 | |
| 48 | def mutate(child: str, genes: list[str]) -> str: |
| 49 | """ |
| 50 | Mutate a random gene of a child with another one from the list. |
| 51 | >>> random.seed(123) |
| 52 | >>> mutate("123456", list("ABCDEF")) |
| 53 | '12345A' |
| 54 | """ |
| 55 | child_list = list(child) |
| 56 | if random.uniform(0, 1) < MUTATION_PROBABILITY: |
| 57 | child_list[random.randint(0, len(child)) - 1] = random.choice(genes) |
| 58 | return "".join(child_list) |
| 59 | |
| 60 | |
| 61 | # Select, crossover and mutate a new population. |