5

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.

Laxmikant
  • 2,046
  • 3
  • 30
  • 44

3 Answers3

8

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
ZdaR
  • 22,343
  • 7
  • 66
  • 87
5

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

Bruce
  • 7,094
  • 1
  • 25
  • 42
  • 1
    One of the great advantages of python is that it has countless libraries and functions for _almost_ every problem. Hence, i'd rather read documentation such as numpy or scipy and apply it to my problem than starting from scratch. (in short: +1) – Daniel Lenz Jul 08 '15 at 13:33
2

You can modify your function as follows:

max_of_three = lambda x, y, z : x if x > y and x > z else (y if y>z  else z)

Your problem was that you did not check, whether x is also larger than z. In your case x is larger than y, therefore, it just returns x and does not compare it to z anymore.

Cleb
  • 25,102
  • 20
  • 116
  • 151