The pythonic way to write constrain () function

What is the best way to write a constraint function? or is there already an inbuilt python function that does this?

Option 1:

def constrain(val, min_val, max_val): if val < min_val: return min_val if val > max_val: return max_val return val 

Option 2:

 def constrain(val, min_val, max_val): if val < min_val: val = min_val elif val > max_val: val = max_val return val 
+5
source share
3 answers

I don't know if this is more "pythonic", but you can use the built-in min() and max() :

 def constrain(val, min_val, max_val): return min(max_val, max(min_val, val)) 
+11
source

If you need to do this for a large number of numbers (arrays full of them), you should probably use Numpy, which has a built-in clip . For simple Python programs, go to the Delgan answer .

+5
source

If you can process many values ​​at a time, you can try to understand the list:

 a = [1,1,5,1,1] b = [7,2,8,5,3] c = [3,3,3,3,3] [min(y,max(x,z)) for x,y,z in zip(a, b, c)] [3, 2, 5, 3, 3] 

or even numpy:

 import numpy as np a = np.array(a) b = np.array(b) c = np.array(c) np.minimum(b, np.maximum(a, c)) np.minimum(b, np.maximum(a, 3)) # just use 3 if they are all the same c.clip(a, b) # or just use NumPy clip method np.clip(c, a, b) array([3, 2, 5, 3, 3]) array([3, 2, 5, 3, 3]) array([3, 2, 5, 3, 3]) array([3, 2, 5, 3, 3]) 
0
source

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


All Articles