Integers value problem and How to provide syntax to depicting Int value in Python

Viewed 34

I am currently meeting the Error which is describe as: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices. I actually understand the problem. However I am not able to fix it in python code as a fact that I'm just a beginner in using Python. the full code is in the link: 'https://homepages.ecs.vuw.ac.nz/~marslast/Code/Ch9/TSP.py' the terminal report is:

((1, 2, 3, 4, 0), 2.4225597326923185)
0.0004763603210449219
Greedy search
Traceback (most recent call last):
  File "TSP.py", line 183, in <module>
    runAll()
  File "TSP.py", line 167, in runAll
    print (greedy(distances))
  File "TSP.py", line 57, in greedy
    dist[:,cityOrder[0]] = np.Inf
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

The invalid code:

    nCities = np.shape(distances)[0]
    distanceTravelled = 0
    
    # Need a version of the matrix we can trash
    dist = distances.copy()

    cityOrder = np.zeros(nCities)
    cityOrder[0] = np.random.randint(nCities)
    dist[:,cityOrder[0]] = np.Inf

    for i in range(nCities-1):
        cityOrder[i+1] = np.argmin(dist[cityOrder[i],:])
        distanceTravelled  += dist[cityOrder[i],cityOrder[i+1]]
        # Now exclude the chance of travelling to that city again
        dist[:,cityOrder[i+1]] = np.Inf
    
    # Now return to the original city
    distanceTravelled += distances[cityOrder[nCities-1],0]

    return cityOrder, distanceTravelled ```
1 Answers

The problem comes from the use of numpy.zeros (doc here). As you can see, the default dtype of the output array is float. And you can't use a float to index an array.

A quick fix would be to specify the dtype of cityOrder to int:

 cityOrder = np.zeros(nCities, dtype=int)
Related