Your solution is fine, but it can be simplified and at the same time made more efficient. If you are using numpy arrays, it is often the case that those small, inner for-loops can be replaced with just a few lines of code. The result should be shorter and run much faster because numpy uses compiled functions to do its work. It can take some time to get used to this style of programming--instead of looping over every element of an array, you operate on the entire array at once. It will help to read examples of this process; look for SO questions like "how do I make XX more efficient in numpy?".
Here is an example NN implementation:
import numpy as npdef NN(A, start):"""Nearest neighbor algorithm. A is an NxN array indicating distance between N locations start is the index of the starting location Returns the path and cost of the found solution""" path = [start] cost = 0 N = A.shape[0] mask = np.ones(N, dtype=bool) # boolean values indicating which # locations have not been visited mask[start] = False for i in range(N-1): last = path[-1] next_ind = np.argmin(A[last][mask]) # find minimum of remaining locations next_loc = np.arange(N)[mask][next_ind] # convert to original location path.append(next_loc) mask[next_loc] = False cost += A[last, next_loc] return path, cost
..and here is an example of this function in use:
# Expected order is 0,2,3,1,4A = np.array([ [0, 2, 1, 2, 2], [2, 0, 2, 1, 1], [1, 2, 0, 1, 2], [2, 1, 1, 0, 2], [2, 1, 2, 2, 0]])print NN(A,0)