title: 2-opt algorithm to solve the Travelling Salesman Problem in Python
body: <p>I couldn't find any complete implementation of the 2-opt algorithm in Python so I am trying to add the missing parts to the code found <a href="http://pedrohfsd.com/2017/08/09/2opt-part1.html" rel="noreferrer">here</a>, which I present below. </p>
  
  <pre><code>def two_opt(route):
       best = route
       improved = True
       while improved:
            improved = False
            for i in range(1, len(route)-2):
                 for j in range(i+1, len(route)):
                      if j-i == 1: continue # changes nothing, skip then
                      new_route = route[:]
                      new_route[i:j] = route[j-1:i-1:-1] # this is the 2woptSwap
                      if cost(new_route) &lt; cost(best):  # what should cost be?
                           best = new_route
                           improved = True
            route = best
       return best
  </code></pre>
  
  <p>In order to complete this code, I made a small program to extract long/lat co-ords from a text file and fill in an adjacency matrix with the cost for each point. Full code, including samples of input co-ordinates and adjacency matrix may be found on <a href="https://codereview.stackexchange.com/questions/207461/extracting-an-adjaceny-matrix-containing-haversine-distance-from-points-on-map">Code Review</a>.</p>
  
  <p>Since I do not know what the <code>cost</code> function is from the code above, my idea was to work out all the costs from one point to another and placed in an adjacency matrix: <code>adj_matrix</code>. This represents how far each point is from the others.</p>
  
  <p>I tried passing my cost/adjacency matrix to the function to use that, however I am unable to calculate the cost given my adjacency matrix.</p>
  
  <pre><code>def main():
      # code to read from file
      # code to append co-ordinates to points and calculate the haversine distance between each point
      route = random.sample(range(10), 10)
      best = two_opt(route, adj_matrix)  # passing my adjacency matrix
      print(best)
  </code></pre>
  
  <blockquote>
    <p>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</p>
  </blockquote>
  
  <p>Another Python 2-opt question: <a href="https://stackoverflow.com/questions/33749268/generate-all-neighbors-for-2opt-in-python">Generate all neighbors for 2OPT in python</a></p>
  
  <p>Any suggestions on how I can <strong>find the correct cost from the adjacency matrix</strong> would be appreciated.</p>