Get the value between min and max values ​​in Python

I did not get the value if it is between the min and max values. If the value is less than min, I want to get the value of min, and if it is more than max, I want to get max. I am using this code now, but is there a built-in or smarter way to do this?

def inBetween(minv, val, maxv): if minv < val < maxv: return val if minv > val: return minv if maxv < val: return maxv print inBetween(2,5,10) 
+4
source share
3 answers

Using min , max :

 >>> def inbetween(minv, val, maxv): ... return min(maxv, max(minv, val)) ... >>> inbetween(2, 5, 10) 5 >>> inbetween(2, 1, 10) 2 >>> inbetween(2, 11, 10) 10 
+8
source

For the record: this type of function is usually called clamp (as in a fix), sometimes clip . The signature you will mostly find for this is clamp(val, minv, maxv) . If you don't like the idiomatic solution using the min and max functions due to utility overhead functions, you can use this solution:

 def clamp(val, minv, maxv): return minv if val < minv else maxv if val > maxv else val 

Quick health check:

 >>> import timeit >>> timeit.timeit("clamp(1, 5, 10)", "def clamp(val, minv, maxv): return min(maxv, max(minv, val))") 1.8955198710000332 >>> timeit.timeit("clamp(1, 5, 10)", "def clamp(val, minv, maxv): return minv if val < minv else maxv if val > maxv else val") 0.5956520039999305 
+2
source

Put them in a list, sort the list, select the middle item.

 >>> def inbetween(minv,val,maxv): ... return sorted([minv,val,maxv])[1] ... >>> inbetween(2,5,10) 5 >>> inbetween(2,1,10) 2 >>> inbetween(2,11,10) 10 
+1
source

Source: https://habr.com/ru/post/1500471/


All Articles