samedi 23 janvier 2021

How to find lowest 3 values in a matrix

So i have this fucntion to find the lowest value in a matrix, and return its position in the matrix, ie its indices:

final_matrix=[[3.57 2.71 9.2 5.63]
              [4.42 1.4 3.53 8.97]
              [1.2 0.33 6.26 7.77]
              [6.36 3.6 8.91 7.42]
              [1.59 0.9 2.4 4.24]] # this changes in my code, im just giving a very simple version of it here

def lowest_values(final_matrix):
best_value=10000 #or any arbitrarily high number 
    for i in range(0,len(final_matrix[:,0])):
        for j in range(0,len(final_matrix[0,:])):
            if final_matrix[i,j]<best_value:
                best_value=final_matrix[i,j]
                lowest_val_i=i
                lowest_val_j=j
    return(lowest_val_i, lowest_val_j)

this returns me (1,2), which just by visual analysis is correct. i want to now find the lowest 3 values - hopefully, to build into this loop. But i really cannot think how! Or at least i dont know how to implement it. I was thinking of some if-else loop, that if the lowest value is already found, then 'void' this one and found 2nd lowest, and then same thing to find the third. But im not sure.

Please dont be too quick to shut this question down - im very new to programming, and very stuck!

Aucun commentaire:

Enregistrer un commentaire