Display the sum of each row of a randomly generated matrix

Asked

Viewed 2,065 times

2

I have the following program that generates a random matrix according to the number of rows and columns desired. In it is also located and displayed the highest value of the elements, and their position (column and row).

How do I display the sum of each row of the generated matrix?

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


def localizaCelulaComMaiorValor(vals):
    resp = (0, 0)
    for lin in range(len(vals)):
        for col in range(len(vals[lin])):
            if vals[lin][col] > vals[resp[0]][resp[1]]:
                resp = (lin, col)
    return resp


qtd = input().split()
qtdLinhas = int(qtd[0])
qtdColunas = int(qtd[1])

valores = gerar(qtdLinhas, qtdColunas, 100, 999)
mostrar(valores, 0, qtdLinhas, 0, qtdColunas)

ondeMaior = localizaCelulaComMaiorValor(valores)
print("O maior valor é", valores[ondeMaior[0]] [ondeMaior[1]],"-> Localizado na coluna",
      ondeMaior[1],"/ linha", ondeMaior[0])

2 answers

1


Greetings, my friend ! I ran your code here, to implement what is asked directly on it, and well, I’ve created the following function that does exactly what you’re asking, take a look at it, it’s not hard at all and I guarantee you’ll understand quickly:

def somaLinhas(vals, colMax):
    n = 1
    for val in vals:
        soma = 0 
        j = 0
        while j < colMax:
            soma = soma + val[j]
            j += 1
        print(f'Soma da linha {n} = {soma}')
        n += 1

When implementing this function in your code and calling, at the end of the code itself, it returns the following output:

Sum of row 1 = 3556
Sum of row 2 = 2452
Sum of row 3 = 2813
Sum of row 4 = 2457

The implemented function works as follows, as the generated matrix has separately the lines with their values, just add each item of these lines, until you get to the last column, when you get to it, it Zera the column but goes to the next line, and so on, if you want to save the values of these sums and not just display them, I advise you to create a list and go giving 'append' as you generate the sums, that is, hugs !

If you want to add the columns the following function is required:

def somaColunas(vals, linMax, colMax):
    j = 0
    n = 0
    soma = 0
    while n < colMax:
        for val in vals:
            soma = soma + val[j]
        j += 1
        n += 1
        print(f'A soma da coluna {n} = {soma}')
        soma = 0

The functioning of this is fundamentally different from the other, however simpler, in this you will add the val element[j] of each line, that is, starting with the first value of all lines, and when you reach the last line, it starts again, however the 'j' is added 1, so he goes to the next column, and this successively until he goes through the whole matrix, I recommend taking a look at this code and trying to replicate it in other applications to train. I hope I’ve helped !

  • The 'n' within the function refers to the line numbering, just to be clear, can be named 'i' without problems, it is only force of habit to name 'n' same.

  • Thank you very much man! It worked here. In case I want to add the columns too, I tried to change the colMax by the linMax and it didn’t work. Since I’m a beginner, I know I’m going soft on something. Where would be the change for me to add and also display each column?

  • Opa, have to do this yes, not just change the input parameter, but the logic of how to go through the matrix, I changed the answer to reply to your comment, take a look there !

1

Since "matrix" is actually a list of lists, just scroll through it with a for simple to iterate through lines (no need to create a range for this, see more details below). And as each line is a list of numbers, just use the function sum to find the sum of its values:

m = gerar(5, 4, 1, 10)
for i, linha in enumerate(m):
    print('soma da linha {} = {}'.format(i + 1, sum(linha)))

I also used the function enumerate to get the line index together with the line itself. When printing, I added 1 to the number, since the indexes start at zero (the first line is zero, the second is 1, etc.). The output is (values vary, since you are using random numbers in generation):

soma da linha 1 = 23
soma da linha 2 = 25
soma da linha 3 = 13
soma da linha 4 = 19
soma da linha 5 = 17

Bonus

You don’t need to use range and len to scroll through the "matrix". In Python, lists (and any object that is everlasting) can be travelled with a for directly, without having to use range (and if you want the index of the elements, just use enumerate, as already seen above). Your methods could be so:

def mostrar(vals):
    for linha in vals: # percorre as linhas da matriz
        for elemento in linha: # percorre os elementos da linha
            print(elemento, end=" ")
        print()
    print()

def localizaCelulaComMaiorValor(vals):
    maior = vals[0][0]
    pos = (0, 0)
    for i, linha in enumerate(vals):
        for j, elemento in enumerate(linha):
            if elemento > maior:
                maior = elemento
                pos = (i, j)
    return pos

Using specific values for rows and columns would only make sense if you wanted to scroll through a part of the matrix. But if you want to go through all the elements, a for simple already resolve (and use the enumerate if you want to know the index of each element - but in the case of the function mostrar, for example, you don’t need the indexes, so make a for directly in the "matrix", which you will already be iterating by your lines - in fact by your elements, which in this case are also lists, and so can also be traversed by another for).

Browser other questions tagged

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