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.
limit-number.pydef limit(num, minimum=1, maximum=255): """Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.
If you want to exclude 0 then change your range to (1,11). The way range works is the lower limit is inclusive where as upper limit is exclusive. On an unrelated note, if your lower limit is 0, you need not include the lower limit and write it as range(11) which is same as range(0,11).
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With