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

Function generate_neighbours

searches/tabu_search.py:32–71  ·  view source on GitHub ↗

Pure implementation of generating a dictionary of neighbors and the cost with each neighbor, given a path file that includes a graph. :param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt) :return dict_of_neighbours: Dictionary with key each node and val

(path)

Source from the content-addressed store, hash-verified

30
31
32def generate_neighbours(path):
33 """
34 Pure implementation of generating a dictionary of neighbors and the cost with each
35 neighbor, given a path file that includes a graph.
36
37 :param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
38 :return dict_of_neighbours: Dictionary with key each node and value a list of lists
39 with the neighbors of the node and the cost (distance) for each neighbor.
40
41 Example of dict_of_neighbours:
42 >>) dict_of_neighbours[a]
43 [[b,20],[c,18],[d,22],[e,26]]
44
45 This indicates the neighbors of node (city) 'a', which has neighbor the node 'b'
46 with distance 20, the node 'c' with distance 18, the node 'd' with distance 22 and
47 the node 'e' with distance 26.
48 """
49
50 dict_of_neighbours = {}
51
52 with open(path) as f:
53 for line in f:
54 if line.split()[0] not in dict_of_neighbours:
55 _list = []
56 _list.append([line.split()[1], line.split()[2]])
57 dict_of_neighbours[line.split()[0]] = _list
58 else:
59 dict_of_neighbours[line.split()[0]].append(
60 [line.split()[1], line.split()[2]]
61 )
62 if line.split()[1] not in dict_of_neighbours:
63 _list = []
64 _list.append([line.split()[0], line.split()[2]])
65 dict_of_neighbours[line.split()[1]] = _list
66 else:
67 dict_of_neighbours[line.split()[1]].append(
68 [line.split()[0], line.split()[2]]
69 )
70
71 return dict_of_neighbours
72
73
74def generate_first_solution(path, dict_of_neighbours):

Callers 1

mainFunction · 0.85

Calls 2

splitMethod · 0.80
appendMethod · 0.45

Tested by

no test coverage detected