@@ -33,15 +33,25 @@ def evaluate(item: str, main_target: str) -> tuple[str, float]:
33
33
34
34
35
35
def crossover (parent_1 : str , parent_2 : str ) -> tuple [str , str ]:
36
- """Slice and combine two string at a random point."""
36
+ """
37
+ Slice and combine two strings at a random point.
38
+ >>> random.seed(42)
39
+ >>> crossover("123456", "abcdef")
40
+ ('12345f', 'abcde6')
41
+ """
37
42
random_slice = random .randint (0 , len (parent_1 ) - 1 )
38
43
child_1 = parent_1 [:random_slice ] + parent_2 [random_slice :]
39
44
child_2 = parent_2 [:random_slice ] + parent_1 [random_slice :]
40
45
return (child_1 , child_2 )
41
46
42
47
43
48
def mutate (child : str , genes : list [str ]) -> str :
44
- """Mutate a random gene of a child with another one from the list."""
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
+ """
45
55
child_list = list (child )
46
56
if random .uniform (0 , 1 ) < MUTATION_PROBABILITY :
47
57
child_list [random .randint (0 , len (child )) - 1 ] = random .choice (genes )
@@ -54,7 +64,25 @@ def select(
54
64
population_score : list [tuple [str , float ]],
55
65
genes : list [str ],
56
66
) -> list [str ]:
57
- """Select the second parent and generate new population"""
67
+ """
68
+ Select the second parent and generate new population
69
+
70
+ >>> import random
71
+ >>> random.seed(42)
72
+ >>> parent_1 = ("123456", 8.0)
73
+ >>> population_score = [("abcdef", 4.0), ("ghijkl", 5.0), ("mnopqr", 7.0)]
74
+ >>> genes = list("ABCDEF")
75
+ >>> pop = []
76
+ >>> child_n = int(parent_1[1]) + 1
77
+ >>> child_n = 10 if child_n >= 10 else child_n
78
+ >>> for _ in range(child_n):
79
+ ... parent_2 = population_score[random.randint(0, len(population_score) - 1)][0]
80
+ ... child_1, child_2 = crossover(parent_1[0], parent_2)
81
+ ... pop.append(mutate(child_1, genes))
82
+ ... pop.append(mutate(child_2, genes))
83
+ >>> len(pop) == (int(parent_1[1]) + 1) * 2
84
+ True
85
+ """
58
86
pop = []
59
87
# Generate more children proportionally to the fitness score.
60
88
child_n = int (parent_1 [1 ] * 100 ) + 1
0 commit comments