Mini Mithi
Mini Mithi

Reputation: 179

a pythonic way to write a constrain() function

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

Upvotes: 9

Views: 8991

Answers (3)

Bas Swinckels
Bas Swinckels

Reputation: 18488

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.

Upvotes: 5

uhoh
uhoh

Reputation: 3745

If you can process a bunch of values at a time, you might try a list comprehension:

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's 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])

Upvotes: 1

Delgan
Delgan

Reputation: 19617

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

Upvotes: 22

Related Questions