Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit a number to be within a specified range? (Python)

Tags:

python

max

min

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.

like image 308
Mantis Toboggan Avatar asked May 13 '11 19:05

Mantis Toboggan


People also ask

How do you limit a number in Python?

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.

How do you exclude a range in Python?

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).


2 Answers

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 
like image 92
Adrien Plisson Avatar answered Sep 20 '22 02:09

Adrien Plisson


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) 
like image 22
Björn Avatar answered Sep 17 '22 02:09

Björn