Working on an exercise from MIT's OpenCourseWare 6.01SC. Problem 3.1.5:
Define a function
clip(lo, x, hi)
that returnslo
ifx
is less thanlo
, returnshi
ifx
is greater thanhi
, and returnsx
otherwise. You can assume thatlo < hi
. ...don't useif
, but usemin
andmax
.
Reformulated in English, if x
is the least of the arguments, return lo
; if x
is the greatest of the arguments, return hi
; otherwise, return x
. Thus:
def clip(lo, x, hi):
if min(lo, x, hi) == x:
return lo
elif max(lo, x, hi) == x:
return hi
else:
return x
Maybe I am not understanding the problem correctly, but I can't figure out how to return a result without using if
at all. How can the function be modified to remove the if/elif/else statements?
Link to original problem 3.1.5
Link to previous problem 3.1.4 (for context)
EDIT:
Comments/answers to this question helped me realize that my original plain English reformulation wasn't a great way to think about the problem. A better way to think about it would have been to determine which of the arguments is between the other two.
One line of code:
#! python3.8
def clip(lo, x, hi):
return max(min(x, hi), lo)
print(clip(1, 2, 3))
print(clip(2, 1, 3))
print(clip(1, 3, 2))
# Output
# 2
# 2
# 2