Problem:
Write a Python function, clip(lo, x, hi) that returns lo if x is less than lo; hi if x is greater than hi; and x otherwise. For this problem, y
def clip(lo, x, hi):
return sorted((lo, x, hi))[1]
This will do the trick without conditional operators.
max(lo,min(hi,x))
min? max? What about:
def clip(lo,x,hi):
return (lo,(hi,x)[x<hi])[x>lo]
Without giving out the whole solution - you don't need to "check" anything. A value limited to lo
from the bottom is what you get from running max(x, lo)
.
Also value clipped to one boundary is not going to be affected by clipping to the other boundary, so you can safely run the result of one correction through another one.
here is also a solution: return min(max(x, lo), hi)
Another solution:
def clip(lo, x, hi):
result = {x: x}
result[min(x, lo)] = lo
result[max(x, hi)] = hi
return result[x]