Reputation: 75
def clip(lo, x, hi):
'''
Takes in three numbers and returns a value based on the value of x.
Returns:
- lo, when x < lo
- hi, when x > hi
- x, otherwise
'''
Upvotes: 1
Views: 1135
Reputation: 21969
Use x = max(low, x)
to get the bigger one out of the two; if x
is smaller than low
, max()
will return low
. Else it'll return x
.
Now that you got the bigger one out of the two, you need to use x = min(high, x)
to get the smaller one out of the new x
and high
.
When combined, you get:
def clip(low, x, high): # Why not use full names?
x = max(low, x)
x = min(high, x)
return x
Which can be further shortened to:
def clip(low, x, high):
return min(high, max(low, x))
Upvotes: 6