1+ # Wikipedia URL- https://en.wikipedia.org/wiki/Adjacency_list
2+ """
3+ Closed Tour Adjacency Representation
4+ ------------------------------------
5+
6+ This converts a path representation (like A→L→G→C→...) into an
7+ adjacency vector form, where each position corresponds to a city in
8+ alphabetical order and the value indicates the next city in the tour.
9+
10+ A closed tour means the last city connects back to the first.
11+
12+ Usage
13+ -----
14+ Run doctests with:
15+ python -m doctest -v closed_tour_adjacency.py
16+ """
17+
18+ from typing import List , Dict
19+
20+
21+ def adjacency_vector_closed (path : List [str ], nodes : List [str ]) -> List [str ]:
22+ """
23+ Generate adjacency vector for a closed tour.
24+
25+ Each position corresponds to a city (from `nodes`) and contains
26+ the next city in the tour. The last city connects back to the first.
27+
28+ Parameters
29+ ----------
30+ path : List[str]
31+ Ordered list of cities representing the tour.
32+ nodes : List[str]
33+ Fixed node order (e.g., ['A', 'B', 'C', ...]).
34+
35+ Returns
36+ -------
37+ List[str]
38+ Adjacency vector aligned with the node order.
39+
40+ Examples
41+ --------
42+ >>> path = list("ALGCFJHEKIBD")
43+ >>> nodes = sorted(set(path))
44+ >>> adjacency_vector_closed(path, nodes)
45+ ['L', 'D', 'F', 'A', 'K', 'J', 'C', 'E', 'B', 'H', 'I', 'G']
46+
47+ >>> adjacency_vector_closed(list("ABCD"), list("ABCD"))
48+ ['B', 'C', 'D', 'A']
49+ """
50+
51+ next_city_map : Dict [str , str ] = {}
52+ total_cities = len (path )
53+
54+ for index , city in enumerate (path ):
55+ # The last city connects to the first (closed tour)
56+ next_city = path [(index + 1 ) % total_cities ]
57+ next_city_map [city ] = next_city
58+
59+ return [next_city_map .get (city , '-' ) for city in nodes ]
60+
61+
62+ if __name__ == "__main__" :
63+ sample_path = list ("ALGCFJHEKIBD" )
64+ ordered_nodes = sorted (set (sample_path ))
65+ adjacency = adjacency_vector_closed (sample_path , ordered_nodes )
66+
67+ print ("Adjacency Representation (alphabetical order):" )
68+ for city , next_city in zip (ordered_nodes , adjacency ):
69+ print (f"{ city } → { next_city } " )
70+
71+ print ("\n Vector form:" )
72+ print (" " .join (adjacency ))
0 commit comments