Romain Lyannaz
Romain Lyannaz

Reputation: 1

Find the shortest path fast

I want to make the shortest path between many points.

I generate an 8x8 matrix, with random values like:

[[ 0 31 33  0 43 10  0  0]
 [31  0 30  0  0 13  0  0]
 [33 30  0 11 12  5  6  0]
 [ 0  0 11  0 15  0 38 11]
 [43  0 12 15  0 39  0  0]
 [10 13  5  0 39  0  3 49]
 [ 0  0  6 38  0  3  0 35]
 [ 0  0  0 11  0 49 35  0]]

Now I want to take the first list and see which is the smaller number. The see where it is in the list and take its position. Next I clear the first list to forget the first point. And put the next position in a new list of path. Then it will do the same for the new point. And at the final when all points are in my list of path it shows me the shortest way.

indm=0
lenm=[]
prochain=max(matrixF[indm])
chemin=[]
long=len(chemin)

while long != n:
    for i in range (n):
        if matrixF[indm,i] <= prochain and matrixF[indm,i]!=0:
            pluspetit=matrixF[indm,i]   
            
    prochainpoint=np.where(matrixF == pluspetit)
       
    chemin.append(prochainpoint)
    
    indm=prochainpoint
    
    for i in range (n):
        matrixF[indm,i]=0
    long=len(chemin)   
    
print(chemin)
print(matrixF)

But I got this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Upvotes: 0

Views: 123

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

This line computes all the indices where matrixF == pluspetit:

prochainpoint=np.where(matrixF == pluspetit)

Problem is, there's more than one, so on your first pass through, prochainpoint ends up as (array([0, 5]), array([5, 0])). You then set indm to prochainpoint, so on your next pass, instead of getting a single value with matrixF[indm,i], you retrieve a 2x2 array of (repeated) values, as if you'd done:

np.array([[matrixF[0,1], matrixF[5,1]]
          [matrixF[5,1], matrixF[0,1]])

Comparing this to prochain (still a scalar value) produces a 2x2 array of boolean results, which you then try to test for truthiness, but numpy doesn't want to guess at whether you mean "are they all true?" or "are any of them true?", so it dumps that decision back on you with the error message.

I'm assuming the problem is with prochainpoint=np.where(matrixF == pluspetit), where you get many results when you presumably only want one, but I'm not clear what the real intent of the line is, so you'll have to figure out what you really intended to do there and replace it with something that consistently computes a single value.

Upvotes: 1

Related Questions