I want to limit a number to be within a certain range. Currently, I am doing the following:
minN = 1 maxN = 10 n = something() #some return value from a function n = max(minN, n) n = min(maxN, n)
This keeps it within minN and maxN, but it doesn’t look very nice. How could I do it better?
PS: FYI, I am using Python 2.6.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
def clamp(n, minn, maxn):
return max(min(maxn, n), minn)
or functionally equivalent:
clamp = lambda n, minn, maxn: max(min(maxn, n), minn)
now, you use:
n = clamp(n, 7, 42)
or make it perfectly clear:
n = minn if n < minn else maxn if n > maxn else n
even clearer:
def clamp(n, minn, maxn):
if n < minn:
return minn
elif n > maxn:
return maxn
else:
return n
Method 2
Simply use numpy.clip() (doc):
n = np.clip(n, minN, maxN)
It also works for whole arrays:
my_array = np.clip(my_array, minN, maxN)
Method 3
If you want to be cute, you can do:
n = sorted([minN, n, maxN])[1]
Method 4
Define a class and have a method for setting the value which performs those validations.
Something vaguely like the below:
class BoundedNumber(object):
def __init__(self, value, min_=1, max_=10):
self.min_ = min_
self.max_ = max_
self.set(value)
def set(self, newValue):
self.n = max(self.min_, min(self.max_, newValue))
# usage
bounded = BoundedNumber(something())
bounded.set(someOtherThing())
bounded2 = BoundedNumber(someValue(), min_=8, max_=10)
bounded2.set(5) # bounded2.n = 8
Method 5
Could you not string together some one-line python conditional statements?
I came across this question when looking for a way to limit pixel values between 0 and 255, and didn’t think that using max() and min() was very readable so wrote the following function:
def clamp(x, minn, maxx): return x if x > minm and x < maxx else (minn if x < minn else maxx)
I would be interested to see how someone more experienced than me would find this way of clamping a value. I assume it must be less efficient than using min() and max(), but it may be useful for someone looking for a more readable (to me at least) function.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0