Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda with nested if else is not working

Tags:

python

lambda

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.

like image 655
Laxmikant Avatar asked Jul 08 '15 13:07

Laxmikant


People also ask

How do you use nested if else in lambda?

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.

Can we use if else in lambda function?

Using if else & elif in lambda functionWe can also use nested if, if-else in lambda function.

Can lambda function have multiple statements?

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.


2 Answers

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
like image 140
ZdaR Avatar answered Sep 24 '22 18:09

ZdaR


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

like image 25
Bruce Avatar answered Sep 24 '22 18:09

Bruce