Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a pythonic way to write a constrain() function

Tags:

python

What's the best way of writing a constrain function? or is there already a builtin 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
like image 842
Mini Mithi Avatar asked Jan 17 '16 11:01

Mini Mithi


2 Answers

I do not know if this is the more "pythonic", but you can use built-in min() and max() like this:

def constrain(val, min_val, max_val):
    return min(max_val, max(min_val, val))
like image 70
Delgan Avatar answered Oct 07 '22 18:10

Delgan


In case you need to do this for a lot of numbers (arrays full of them), you should probably be using Numpy, which has a built-in clip function. For simple Python programs, go with Delgan's answer.

like image 37
Bas Swinckels Avatar answered Oct 07 '22 20:10

Bas Swinckels