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

Function find_neighborhood

searches/tabu_search.py:127–185  ·  view source on GitHub ↗

Pure implementation of generating the neighborhood (sorted by total distance of each solution from lowest to highest) of a solution with 1-1 exchange method, that means we exchange each node in a solution with each other node and generating a number of solution named neighborhood.

(solution, dict_of_neighbours)

Source from the content-addressed store, hash-verified

125
126
127def find_neighborhood(solution, dict_of_neighbours):
128 """
129 Pure implementation of generating the neighborhood (sorted by total distance of
130 each solution from lowest to highest) of a solution with 1-1 exchange method, that
131 means we exchange each node in a solution with each other node and generating a
132 number of solution named neighborhood.
133
134 :param solution: The solution in which we want to find the neighborhood.
135 :param dict_of_neighbours: Dictionary with key each node and value a list of lists
136 with the neighbors of the node and the cost (distance) for each neighbor.
137 :return neighborhood_of_solution: A list that includes the solutions and the total
138 distance of each solution (in form of list) that are produced with 1-1 exchange
139 from the solution that the method took as an input
140
141 Example:
142 >>> find_neighborhood(['a', 'c', 'b', 'd', 'e', 'a'],
143 ... {'a': [['b', '20'], ['c', '18'], ['d', '22'], ['e', '26']],
144 ... 'c': [['a', '18'], ['b', '10'], ['d', '23'], ['e', '24']],
145 ... 'b': [['a', '20'], ['c', '10'], ['d', '11'], ['e', '12']],
146 ... 'e': [['a', '26'], ['b', '12'], ['c', '24'], ['d', '40']],
147 ... 'd': [['a', '22'], ['b', '11'], ['c', '23'], ['e', '40']]}
148 ... ) # doctest: +NORMALIZE_WHITESPACE
149 [['a', 'e', 'b', 'd', 'c', 'a', 90],
150 ['a', 'c', 'd', 'b', 'e', 'a', 90],
151 ['a', 'd', 'b', 'c', 'e', 'a', 93],
152 ['a', 'c', 'b', 'e', 'd', 'a', 102],
153 ['a', 'c', 'e', 'd', 'b', 'a', 113],
154 ['a', 'b', 'c', 'd', 'e', 'a', 119]]
155 """
156
157 neighborhood_of_solution = []
158
159 for n in solution[1:-1]:
160 idx1 = solution.index(n)
161 for kn in solution[1:-1]:
162 idx2 = solution.index(kn)
163 if n == kn:
164 continue
165
166 _tmp = copy.deepcopy(solution)
167 _tmp[idx1] = kn
168 _tmp[idx2] = n
169
170 distance = 0
171
172 for k in _tmp[:-1]:
173 next_node = _tmp[_tmp.index(k) + 1]
174 for i in dict_of_neighbours[k]:
175 if i[0] == next_node:
176 distance = distance + int(i[1])
177 _tmp.append(distance)
178
179 if _tmp not in neighborhood_of_solution:
180 neighborhood_of_solution.append(_tmp)
181
182 index_of_last_item_in_the_list = len(neighborhood_of_solution[0]) - 1
183
184 neighborhood_of_solution.sort(key=lambda x: x[index_of_last_item_in_the_list])

Callers 1

tabu_searchFunction · 0.85

Calls 2

sortMethod · 0.80
appendMethod · 0.45

Tested by

no test coverage detected