MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / crossover

Function crossover

genetic_algorithm/basic_string.py:35–45  ·  view source on GitHub ↗

Slice and combine two strings at a random point. >>> random.seed(42) >>> crossover("123456", "abcdef") ('12345f', 'abcde6')

(parent_1: str, parent_2: str)

Source from the content-addressed store, hash-verified

33
34
35def crossover(parent_1: str, parent_2: str) -> tuple[str, str]:
36 """
37 Slice and combine two strings at a random point.
38 >>> random.seed(42)
39 >>> crossover("123456", "abcdef")
40 ('12345f', 'abcde6')
41 """
42 random_slice = random.randint(0, len(parent_1) - 1)
43 child_1 = parent_1[:random_slice] + parent_2[random_slice:]
44 child_2 = parent_2[:random_slice] + parent_1[random_slice:]
45 return (child_1, child_2)
46
47
48def mutate(child: str, genes: list[str]) -> str:

Callers 1

selectFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected