Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a value between min and max values in Python

I wan't to get a value if it's between min and max values. If the value is smaller than min, I want to get the min value and if it's greater than max I want to get the max. I use this code now, but is there an inbuilt or smarter way to do it?

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) 
like image 804
PeetWc Avatar asked Sep 04 '13 08:09

PeetWc


1 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
like image 134
falsetru Avatar answered Oct 04 '22 21:10

falsetru