Skip to content

Commit 4259348

Browse files
KelvinPuyampre-commit-ci[bot]cclauss
authored
Add doctests in all functions in basic_string.py (#11374)
* Add doctests in all functions in basic_string.py * Revert back to original basic_string.py * Add doctest in basic_string.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update genetic_algorithm/basic_string.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent a42eb35 commit 4259348

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

genetic_algorithm/basic_string.py

+28-3
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,25 @@ def evaluate(item: str, main_target: str) -> tuple[str, float]:
3333

3434

3535
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+
"""
3742
random_slice = random.randint(0, len(parent_1) - 1)
3843
child_1 = parent_1[:random_slice] + parent_2[random_slice:]
3944
child_2 = parent_2[:random_slice] + parent_1[random_slice:]
4045
return (child_1, child_2)
4146

4247

4348
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+
"""
4555
child_list = list(child)
4656
if random.uniform(0, 1) < MUTATION_PROBABILITY:
4757
child_list[random.randint(0, len(child)) - 1] = random.choice(genes)
@@ -54,7 +64,22 @@ def select(
5464
population_score: list[tuple[str, float]],
5565
genes: list[str],
5666
) -> list[str]:
57-
"""Select the second parent and generate new population"""
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+
"""
5883
pop = []
5984
# Generate more children proportionally to the fitness score.
6085
child_n = int(parent_1[1] * 100) + 1

0 commit comments

Comments
 (0)