Skip to content

Commit 3f3b4e5

Browse files
Update genetic_algorithm/travelling_salesman_problem.py
Co-authored-by: priya-sundaram-dev <oc-409d01@agentmail.to>
1 parent 3440ea5 commit 3f3b4e5

1 file changed

Lines changed: 13 additions & 6 deletions

File tree

‎genetic_algorithm/travelling_salesman_problem.py‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -321,15 +321,22 @@ def crossing(
321321

322322
def mutate(chromosome: list[int], mutation_probability: float) -> list[int]:
323323
"""
324-
Population variation
325-
>>> mutate([0,1,0],mutation_probability=0)
326-
[0, 1, 0]
327-
>>> mutate([0,1,0],mutation_probability=1)
324+
Population variation: swap two interior cities (endpoints stay at 0).
325+
326+
>>> mutate([0, 1, 0], mutation_probability=0) # no mutation -> unchanged
328327
[0, 1, 0]
329-
>>> mutate([],mutation_probability=1)
328+
>>> import random
329+
>>> random.seed(1)
330+
>>> mutate([0, 1, 2, 3, 0], mutation_probability=1) # swaps two interior cities
331+
[0, 2, 1, 3, 0]
332+
333+
An empty chromosome has no interior cities to swap; match only the exception
334+
type since the exact stdlib message changes across Python versions.
335+
336+
>>> mutate([], mutation_probability=1) # doctest: +IGNORE_EXCEPTION_DETAIL
330337
Traceback (most recent call last):
331338
...
332-
ValueError: empty range in randrange(1, -1)
339+
ValueError
333340
"""
334341
new_chromosome = copy.deepcopy(chromosome)
335342
if random.random() <= mutation_probability:

0 commit comments

Comments
 (0)