Skip to content

Commit 2a2cb56

Browse files
Apply batched suggestions from code review
Co-authored-by: priya-sundaram-dev <oc-409d01@agentmail.to>
1 parent 7088f25 commit 2a2cb56

1 file changed

Lines changed: 25 additions & 8 deletions

File tree

‎genetic_algorithm/ordinal_representation.py‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
88
"""
99

10-
from collections.abc import Iterator
10+
from collections.abc import Iterator, Sequence
1111

1212

13-
def ordinal_representation_closed(path: list[str], nodes: list[str]) -> Iterator[int]:
13+
def ordinal_representation_closed(path: Sequence[str], nodes: Sequence[str]) -> Iterator[int]:
1414
"""
1515
Generate the ordinal representation for a closed path.
1616
@@ -52,15 +52,32 @@ def ordinal_representation_closed(path: list[str], nodes: list[str]) -> Iterator
5252
msg = "path and nodes must contain the same values"
5353
raise ValueError(msg)
5454

55-
reference = nodes.copy()
55+
reference = list(nodes)
5656
for city in path:
5757
yield (index := reference.index(city) + 1) # 1-based index
5858
reference.pop(index - 1)
5959

6060

61+
def tour_from_ordinal(ordinal: list[int], nodes: list[str]) -> list[str]:
62+
"""
63+
Decode an ordinal representation back into a tour.
64+
65+
This is the exact inverse of ``ordinal_representation_closed``. It is what
66+
makes ordinal encoding useful in a genetic algorithm: an ordinary one-point
67+
crossover of two ordinal vectors always decodes to a valid tour, with no
68+
repair step needed.
69+
70+
>>> nodes = list("ABCDEFGHIJKL")
71+
>>> path = list("GLADBIKEHJFC")
72+
>>> encoded = list(ordinal_representation_closed(path, nodes))
73+
>>> tour_from_ordinal(encoded, nodes) == path
74+
True
75+
"""
76+
reference = nodes.copy()
77+
return [reference.pop(index - 1) for index in ordinal]
78+
79+
6180
if __name__ == "__main__":
62-
sample_path = list("ODGLAHKMBJFCNIE")
63-
all_nodes = sorted(set(sample_path))
64-
print("Ordinal Representation:")
65-
ordinal_values = ordinal_representation_closed(sample_path, all_nodes)
66-
print(" ".join(map(str, ordinal_values)))
81+
import doctest
82+
83+
doctest.testmod()

0 commit comments

Comments
 (0)