How can I get the highest value of a matrix with Lambda function in Python

Asked

Viewed 165 times

2

In a list it is possible with the method "reduce" to achieve the highest value, but in a matrix I am not able to obtain the highest value of it:

from functools import reduce

matriz = [[4, 2, 56], [7, 46, 10], [3, 89, 2]]
print(matriz)
result = reduce((lambda x , y: x if (x > y) else y), matriz)
print(result)

The result I get is:

[7, 46, 10]

I would like to pull a single value within the entire matrix that is the largest of the rest.

  • Is it mandatory to use a matrix? It can be a converted matrix?

  • Yes, it is mandatory to use matrix.

  • But the use of reduce ?

  • No, as long as you stay with the lambda function to find the lowest value in the list.

2 answers

1

You can iterate your matrix within the second reduce argument:

from functools import reduce
matriz = [[4, 2, 56], [7, 46, 10], [3, 89, 2]]
print(matriz)
result = reduce((lambda x , y: x if (x > y) else y), [item for sublista in matriz for item in sublista])
print(result)

Exit:

[[4, 2, 56], [7, 46, 10], [3, 89, 2]]
89

1


As his matriz is a list of lists (a list in which each element is another list), use reduce this way you will only go through the first level (ie you will be comparing whether one list is larger than another). To compare the numbers, you can use the module itertools:

from functools import reduce
from itertools import chain

matriz = [[4, 2, 56], [7, 46, 10], [3, 89, 2]]
result = reduce(lambda x , y: x if x > y else y, chain.from_iterable(matriz))
print(result) # 89

chain.from_iterable takes all the sub-lists and transforms them into a single eternity, in which each element will be one of the numbers. So you can compare them correctly with the lambda (note also that the parentheses around the labmda are redundant and can be removed).


You said in the comments what to use reduce is not mandatory, only the lambda. Therefore, one could be made loop simple:

matriz = [[4, 2, 56], [7, 46, 10], [3, 89, 2]]
maior = lambda x , y: x if x > y else y
result = float('-inf')
for linha in matriz:
    for numero in linha:
        result = maior(result, numero)
print(result) # 89

The detail is that I start result with "least infinite" (the least possible value), so in the first comparison the first element of the matrix will surely be greater than it. In the other iterations, he compares the result with each element, and in the end we have the largest.


Note: if it was not mandatory to use the lambda, it would be simpler to use max, along with chain.from_iterable:

result = max(chain.from_iterable(matriz))

Browser other questions tagged

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