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])
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.
– Absolver
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?
– MSSantana
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 !
– Absolver