Python: find product of highest value of each array list

0

Dear Sirs, I already researched a lot before posting my doubt. I'm already discouraged.

This is a university job. If you can give me a tip, I appreciate it.

The exercise asks: "(c) What is the product of the highest values of each of the lines;"

Below is the code ... Thanks.

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")
    
asked by anonymous 24.02.2018 / 22:46

2 answers

1
Complementing the Isac response, it is also possible to calculate the product of the largest numbers of each row in the array using a combination of the max functions, which obtains the largest value of an iterable, map , which applies a function over an iterable and reduce , which reduces an iterable to a scalar, based on a function. In this case, we make map(max, matrix) to get an iterable with all the largest values of each row of the array 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 at Ideone | Repl.it

The code is practically the equivalent of Isac:

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

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

    
25.02.2018 / 18:19
1

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

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

With this function the calculation of the product 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 array in the right place because of the indentation. In addition, if you want to add m rows it does not matter whether you go from 1 to m or 0 to m-1 and so it becomes easier to use range(m) instead of range(1, m+1) .

Rewrite the array 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 any need to use the max and posicao that it had. I do however leave an important warning in the sense of not using names that already exist in native functions like max because it ends up giving you strange errors when you need to use them.

You can also combine the product's calculation with finding the largest 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 asked.

See how it works in Ideone

    
24.02.2018 / 23:21