Lambda python function

Asked

Viewed 227 times

1

I’m trying to do a python lambda function that finds the largest element in a list that has length N. If you make the following code, you’d be right?

maior = reduce((lambda x,y: x if (x > y) eles y), lista)

Or as it is for a list of length N I would have to do otherwise?

  • Put an example so that your code is executable and testable, otherwise the question can be deleted

  • 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)

3 answers

0

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
    • 5 > 4 = True, return x 5
  • 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.

0

At first it is correct, apart from the typo in Else. The simplest way to check is to do assert.

from functools import reduce
lista = [1,2,3,4,5,6]
maior = reduce((lambda x,y: x if (x > y) else y), lista)
assert maior == 6
  • Because I was in doubt, since you ask for a list of length N, without giving the size of the list, so it could be any list and my code would have to be something Generic that works on any list.

  • At no time does you use a start / end delimiter in reduce(), so it is ok for your goal. Take a look at the documentation, it’ll help you. "Apply Function of two Arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) Calculates ((((1+2)+3)+4)+5)."

0

If your intention is to implement a function lambda to verify the maior element of any list with N elements, you can use the following algorithm...

from functools import reduce

lista = list(map(int, input('Digite todos os valores da lista: ').split()))
maior = reduce((lambda x, y: x if (x > y) else y), lista)
print(f'\033[32mO maior elemento da lista é: {maior}')

Note that when we run this algorithm we receive the following message: Digite todos os valores da lista: . Right now we must type all the values of the list in the same line, separated for a single space and then press enter.

From that moment, the algorithm will assemble a list, containing all values passed by input. Then the variable of maior store only the highest value verified by the lambda function. Later, the algorithm will display the maior value among those inserted in the list.

Observing

The list formed by this algorithm can have as many elements as the user wants.

Browser other questions tagged

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