Skip to content

Commit 0482238

Browse files
committed
Create ordinal_representation.py
1 parent e2a78d4 commit 0482238

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Ordinal Representation of a Closed Tour
3+
---------------------------------------
4+
5+
Converts a path (e.g., a Hamiltonian tour) into its ordinal
6+
representation based on a fixed alphabetical node reference.
7+
8+
"""
9+
10+
11+
def ordinal_representation_closed(path: list[str], nodes: list[str]) -> list[int]:
12+
"""
13+
Generate the ordinal representation for a closed path.
14+
15+
Each element in the result denotes the position (1-indexed)
16+
of the corresponding city in the current reference list,
17+
which shrinks as cities are removed.
18+
19+
Parameters
20+
----------
21+
path : list[str]
22+
Sequence of cities in the closed tour.
23+
nodes : list[str]
24+
Reference list of all nodes, in fixed order (e.g., A-Z).
25+
26+
Returns
27+
-------
28+
list[int]
29+
Ordinal representation of the path.
30+
31+
Examples
32+
--------
33+
>>> path = list("GLADBIKEHJFC")
34+
>>> nodes = list("ABCDEFGHIJKL")
35+
>>> ordinal_representation_closed(path, nodes)
36+
[7, 11, 1, 3, 1, 5, 6, 2, 3, 3, 2, 1]
37+
38+
>>> path = list("ALGC FJHEKIBD".replace(" ", ""))
39+
>>> nodes = sorted(set(path))
40+
>>> ordinal_representation_closed(path, nodes)
41+
[1, 11, 6, 2, 4, 6, 4, 3, 4, 3, 1, 1]
42+
"""
43+
reference = nodes.copy()
44+
ordinal = []
45+
46+
for city in path:
47+
index = reference.index(city) + 1 # 1-based index
48+
ordinal.append(index)
49+
reference.pop(index - 1)
50+
51+
return ordinal
52+
53+
54+
if __name__ == "__main__":
55+
sample_path = list("ODGLAHKMBJFCNIE")
56+
all_nodes = sorted(set(sample_path))
57+
ordinal_values = ordinal_representation_closed(sample_path, all_nodes)
58+
59+
print("Ordinal Representation:")
60+
print(" ".join(map(str, ordinal_values)))

0 commit comments

Comments
 (0)