Home > Software design >  Lambda Function can be used in this case, or just a def function?
Lambda Function can be used in this case, or just a def function?

Time:09-16

In a statement defined as:

def max_value(number1, number2, number3, number4, number5)
    value = number1
    if number1 <= number2:
         value = number2
    if number2 <= number3:
         value = number3
    if number3 <= number4:
         value = number4
    if number4 <= number5:
         value = number5
    return value

What would be the correct function for using lambda?

max_value_lambda = lambda ???????

CodePudding user response:

Would it work to create a list with all the numbers and then apply lambda function?

Something like:

list = [number1, number2, number3]
max_lambda = lambda x: max(x)
print(max_lambda(list))

CodePudding user response:

Try:

max_value_lambda = lambda number1, number2, number3, number4, number5: max(
    number1, number2, number3, number4, number5
)

print(max_value_lambda(1, 6, 4, 3, 2))

Prints:

6

Or for arbitrary number of arguments:

max_value_lambda = lambda *args: max(args)

print(max_value_lambda(1, 6, 4, 3, 2))
  • Related