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.

9
  • 3
    Look at your logic closely. X is bigger than Y, so it returns X. Commented Jul 8, 2015 at 13:25
  • 1
    Elaborating on what Morgan explained: It never gets to your else... Commented Jul 8, 2015 at 13:27
  • This has nothing to do with lambdas. Commented Jul 8, 2015 at 13:27
  • 2
    Not the problem with your function, but there is a builtin max function you could use: max_of_three = lambda x, y, z : max(x,y,z) Commented Jul 8, 2015 at 13:29
  • max (x, y, z) or something like x if x > y and x > z else y if y > z else z Commented Jul 8, 2015 at 13:29

3 Answers 3

9

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
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.