I'm newbie to Python and am learning lambda
expressions at the moment. I was solving a tutorial program
Define a function
max_of_three()
that takes three numbers as arguments and returns the largest of them.
I've gone through this old post and tried without success:
>>> max_of_three = lambda x, y, z : x if x > y else (y if y>z else z)
>>> max_of_three(91,2,322)
91
Why it's not returning Z? It's X.
You can have nested if else in lambda function. Following is the syntax of Python Lambda Function with if else inside another if else, meaning nested if else. value_1 is returned if condition_1 is true, else condition_2 is checked. value_2 is returned if condition_2 is true, else value_3 is returned.
Using if else & elif in lambda functionWe can also use nested if, if-else in lambda function.
Yes. As alex's answer points out, sorted() is a version of sort that creates a new list, rather than sorting in-place, and can be chained.
Currently you are using if x > y
which only compares the x
and y
, but you need to compare the x
with z
as well at the same step.
max_of_three = lambda x, y, z: x if x > y and x > z else (y if y > z else z)
print max_of_three(91, 2, 322)
>>> 322
or, make it simpler:
max_of_three=lambda x,y,z:max((x,y,z))
max_of_three(1,2,3)
3
I know it's cheating, but using the language primitives is usually easier :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With