Python: find product of the highest value of each matrix list

Asked

Viewed 912 times

0

Dear Ladies and Gentlemen(s), I’ve done a lot of research before posting my question. I am already discouraged.

This is a university job. If you can give me a hint, I’d appreciate it.

The exercise calls for: "(c) What is the product of the highest values of each line;"

Below is the code... Thank you.

import random

#cria matriz
matriz = []
#usuário digita a Qtd de linhas e colunas desejadas;
m = int(input("Informe a qtd de linhas desejadas na Matriz: "))
n = int(input("Informe a qtd de colunas desejadas na Matriz: "))
#usuário define o intervalo para geração automática de valores.
a = int(input("Defina o início do intervalo para geração aleatória: "))
b = int(input("Defina o fim do intervalo para geração aleatória: "))

max = None  # Armazena o maior valor
posicao = (0, 0)  # Armazena a posição do maior valor


for i in range(1, m+1):
    linha = []
    for j in range(1, n+1):
        x = float(random.uniform(a, b)) #gera números aleatórios dentro do intervalo definido
        if max is None or x > max:
            max = x
            posicao = (i, j)

        linha.append(x)
        matriz.append(linha)


print("----------------------------")
print("Respostas das alternativas")
print("----------------------------")
print("(A) A matriz gerada aleatoriamente é: ", matriz)
print("(B) O maior valor está na posição {} e vale {}".format(posicao, max))
print("(C) ainda não consegui resolver")

2 answers

1


Complementing the Isac response, it is also possible to calculate the product of the largest numbers of each matrix row using a combination of functions max, which obtains the highest value of an eternal, map, which applies a function on an iterable and reduce, that reduces an iterable to a scalar, based on a function. In this case, we do map(max, matrix) to obtain an iterable with all the highest values of each matrix row and calculate the product of these with the function reduce:

from operator import mul
from functools import reduce

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

result = reduce(mul, map(max, matrix), 1)

print("Resultado:", result)

See working on Ideone | Repl.it

The code is practically the equivalent of the one presented by Isac:

produto = 1
for linha in matriz:
    produto *= max(linha)

But it is good to always know the alternatives and it may happen to be interesting to apply this functional solution.

  • Thank you Anderson! :)

  • I didn’t even think of reduce. I’d say it gets more pythonic :)

  • @Isac, not necessarily. With the reduce the solution is closer to the functional paradigm, which can bring advantages in some projects, but in a way, impairs the readability. The noose for is much easier to read and understand what is done. For a simple solution like this, I would opt for the readability of for even.

1

To calculate the highest value of each row you can use the native function max. It can either receive the various values or a list of values:

>>> max(1,2,3)
3
>>> max([3,5,1,6,2])
6

With this function the product calculation of the highest values of each line becomes:

produto = 1
for linha in matriz:
    produto *= max(linha)

However your code did not have the addition of the line to the matrix in the right place due to indentation. In addition to this you want to add m lines is indifferent if it goes from 1 to m or of 0 to m-1 and therefore it becomes easier to use range(m) instead of range(1, m+1).

So rewrite the matrix reading to:

for i in range(m): # range(m) em vez de range(1, m+1)
    linha = []
    for j in range(n): # aqui também range simplificado
        x = float(random.uniform(a, b)) #gera números aleatórios dentro do intervalo definido
        linha.append(x)

    matriz.append(linha) # não ao mesmo nivel do linha.append(x)

With this simplification to calculate the maximum there is no longer a need to use the max and posicao that I had. I do, however, warn against using names that already exist in native functions such as max because it ends up giving you strange mistakes when you need to use the same.

You can also combine the product calculation with the largest finding and its position using the function index, which allows you to find the position of an element in the list:

produto = 1
maior = max([max(linha) for linha in matriz]) # achar o maior

for posicao, linha in enumerate(matriz):
    produto *= max(linha)
    if maior in linha: # se o maior está nesta linha
        posicao_maior = (posicao, linha.index(maior)) # guardar a sua posição

And with so little code answers the three questions requested.

See how it works in Ideone

  • Thank you very much! I will check :)

  • Isac, thank you so much. You helped me so much! I managed to resolve the issues with your help. I wish you a good night! :)

  • @Wilsonjunior I’m glad I helped. Any questions you have just ask.

Browser other questions tagged

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