Skip to content

Add doctests in all functions in basic_string.py #11374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 20, 2024
Merged
Changes from 4 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
34 changes: 31 additions & 3 deletions genetic_algorithm/basic_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,25 @@ def evaluate(item: str, main_target: str) -> tuple[str, float]:


def crossover(parent_1: str, parent_2: str) -> tuple[str, str]:
"""Slice and combine two string at a random point."""
"""
Slice and combine two strings at a random point.
>>> random.seed(42)
>>> crossover("123456", "abcdef")
('12345f', 'abcde6')
"""
random_slice = random.randint(0, len(parent_1) - 1)
child_1 = parent_1[:random_slice] + parent_2[random_slice:]
child_2 = parent_2[:random_slice] + parent_1[random_slice:]
return (child_1, child_2)


def mutate(child: str, genes: list[str]) -> str:
"""Mutate a random gene of a child with another one from the list."""
"""
Mutate a random gene of a child with another one from the list.
>>> random.seed(123)
>>> mutate("123456", list("ABCDEF"))
'12345A'
"""
child_list = list(child)
if random.uniform(0, 1) < MUTATION_PROBABILITY:
child_list[random.randint(0, len(child)) - 1] = random.choice(genes)
Expand All @@ -54,7 +64,25 @@ def select(
population_score: list[tuple[str, float]],
genes: list[str],
) -> list[str]:
"""Select the second parent and generate new population"""
"""
Select the second parent and generate new population

>>> import random
>>> random.seed(42)
>>> parent_1 = ("123456", 8.0)
>>> population_score = [("abcdef", 4.0), ("ghijkl", 5.0), ("mnopqr", 7.0)]
>>> genes = list("ABCDEF")
>>> pop = []
>>> child_n = int(parent_1[1]) + 1
>>> child_n = 10 if child_n >= 10 else child_n
>>> for _ in range(child_n):
... parent_2 = population_score[random.randint(0, len(population_score) - 1)][0]
... child_1, child_2 = crossover(parent_1[0], parent_2)
... pop.append(mutate(child_1, genes))
... pop.append(mutate(child_2, genes))
>>> len(pop) == (int(parent_1[1]) + 1) * 2
True
"""
pop = []
# Generate more children proportionally to the fitness score.
child_n = int(parent_1[1] * 100) + 1
Expand Down