user5724028
user5724028

Reputation:

Python - Nested Function, Parentheses order

I had a problem where I was required to write a function where if x was less than lo the output would be lo and if x was greater than hi the output would be hi. Otherwise the output would be x. The solution to the problem was:

def hilo(lo, x, hi):

    return min(max(x, lo), hi)

Can someone give me an explanation as to the order of the parentheses in the return statement? I tried writing like this:

 return min(max(x, lo, hi))  

but obviously, that didn't work.

Upvotes: 0

Views: 82

Answers (2)

Mark Reed
Mark Reed

Reputation: 95252

min(max(x,lo), hi) means

  1. call max with x and lo as parameters.
  2. call min with the return value of that call and hi as parameters.

Assuming the semantics of the values lo and hi and the functions min and max implied by their names, this logic first figures out which is bigger between x and lo, and then which is smaller between that and hi. The result is thus guaranteed to be no less than lo and no more than hi; if x is in that range, then x itself is returned, otherwise the closest end of the range to x is returned.

Whereas, min(max(x,lo,hi) means:

  1. call max with x, lo, and hi as parameters
  2. call min with the return value of that call as the only parameter.

Given the same assumptions about the names matching the semantics, that makes no sense, as min with only one argument, even if it weren't an error, would just return that one argument unchanged. The above would always return whichever is bigger between hi and x, while lo wouldn't enter into it at all.

Upvotes: 3

Matti
Matti

Reputation: 106

The function in the innermost parenthesis max(x, lo) is executed first. This returns the bigger value between x and lo. Then the outer function min is executed with the remaining 2 arguments x or lo and hi.

The max function won't work with 3 arguments as you tried with max(x, lo, hi). Neither does the min with 1 argument, what max would be returning.

Upvotes: 1

Related Questions