Adding and sorting row of matrices in python

Asked

Viewed 478 times

0

The program below generates a random matrix, according to the amount of lines desired.

def gerar(nLins, nCols, min, max):
    from random import randint
    vals = [None] * nLins
    for i in range(nLins):
        vals[i] = [0] * nCols
        for j in range(nCols):
            vals[i][j] = randint(min, max)
    return vals


def mostrar(vals, linMin, linMax, colMin, colMax):
    for i in range(linMin, linMax):
        for j in range(colMin, colMax):
            print(vals[i][j], end=" ")
        print()
    print()
    return None




qtd = input().split()
qtdLinhas = int(qtd[0])
qtdColunas = int(qtd[1])
valores = gerar(qtdLinhas, qtdColunas, 10, 99)
mostrar(valores, 0, qtdLinhas, 0, qtdColunas)

In this case, I would like to know how I could sum each row of the matrix and generate a new matrix with the rows of the matrix in ascending order of the sum of its values?

Example:

I want a 5 x 6 matrix

The matrix is generated:

13 28 45 50 26 10
27 24 22 33 88 11
90 25 85 23 76 55
77 15 31 29 13 14
66 41 50 20 47 11

With it, the second matrix is generated with the ordered lines according to their sum, in ascending order:

13 28 45 50 26 10 
77 15 31 29 13 14 
27 24 22 33 88 11 
66 41 50 20 47 11 
90 25 85 23 76 55 

Since their sums in ascending order give 172 in the first line, 179 in the second line, 205 in the third line, and so on...

1 answer

1

Use the method sort.

You can pass in the parameter key a callback function to generate the value that will be used to compare and organize matrix items. For this case just use the function sum to sum up all the items on each list. The results of the sums will be compared internally and the matrix will be organized in ascending order by the results of the sums:

valores = [
    [13, 28, 45, 50, 26, 10],
    [27, 24, 22, 33, 88, 11],
    [90, 25, 85, 23, 76, 55],
    [77, 15, 31, 29, 13, 14],
    [66, 41, 50, 20, 47, 11]
]

valores.sort(key=sum)
  • Could you give me an example? I could not apply generating the matrix as I mentioned above and applying this concept you passed.

  • Here has the code working. I don’t understand the difficulty, since you can use the code literally as it is in the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.