Hello, your idea is very close to correct. It would be interesting to specify which version of Python was used. Because the function reduce
was a function built-in python2 (which is already legacy). From Python3 the function reduce
was moved to a module called functools
, so we need to import it. To understand the solution well, let’s go in parts:
1. How to create functions with lambda expressions:
To sign a lambda function we use the same idea of assignment to variables.
variavel = valor
In this case the "value" that will be saved with that name is a lambda function, example:
comparacao = lambda x, y: x > y # Esta é uma função lambda que diz se x é maior que y
2. Understanding the syntax of reduce
:
reduce(funcao, iteravel)
This means that we will apply the function passed as parameter over all elements of an iterable (usually a list []
or a tuple ()
). In this case, let’s compare x
and y
, one of these terms will be the largest, so the result of this operation will be used in the next comparison with another element, until we get to the last. For example in this short list: [3, 5, 4]
the steps are:
x = 3
and y = 5
- 3 > 5 =
False
, return y 5
x = 5
, and y = 4
- The largest calculated element is 5.
Now that we understand all this, to make the solution as you described, it is necessary that there is a way to call this function. In this case, as it was written, it would not be possible to call it, because the name of the function already received the direct reduce, but there was no way to pass a list as parameter because it was not a function. To pass the list as desired it is necessary to follow the structure:
from functools import reduce # Lembrando que temos de importar o reduce de sua biblioteca do Python.
maior = lambda lista: reduce(lambda x, y: x if (x > y) else y, lista)
Note how we have 2 different planes, one is the lambda that allows us to call the function and pass the list, and the other is a function within of reduce
to be applied over the list. With this, your function is already ready to return the largest element in the list. I hope I helped you understand well!
Editing:
OBS: The numerical list can be any size you want, you don’t need to change your algorithm because of the list size.
Put an example so that your code is executable and testable, otherwise the question can be deleted
– Evilmaax
Do you have to do this using a lambda expression? I wonder why Python offers a built-in function max() which returns the largest item in an iterable. Ex:
maior = max(lista)
– Augusto Vasques