Python Forum

Full Version: is there a single function to confine a number between two others?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
is there a single function to confine a number between two others? i know i can do it with min() and max(), but that actually looks ugly. this should use 3 arguments.
You're asking if one number has a value between two others? I'd do that initially with the operators like

lower <= n <= upper
I'm not sure this is what you meant by "confine"...

If they're all integers, you can also test it from a range, but that won't work for floats.

n in range(lower, upper + 1)
It's quite simple to mimic built-in range for floats:

def float_range(start, stop, step):
    current = float(start)
    while current < stop:
        yield current
        current += step

print(*float_range(1, 3, 0.25)) -> 1.0 1.25 1.5 1.75 2.0 2.25 2.5 2.75
this:
def confine(a,n,b):
    n=max(n,a)
    n=min(n,b)
    return n
I've never heard of a single function that does that operation. I don't see anything wrong with your function as a solution. If you were golfing, you could reduce it to

return min(max(n,a),b)
but if your objection to the first is how it reads, I don't think that's an improvement.
how it reads in code the i want to be readable is my concern. the reduced code does not make it a readable as i want, hence my step-by-step in my confine() function.

i'm fine with using my own function. i have it in my big collection. i was just interested if i missed one in the Python library. but now i'm curious if someone can come up with a better name.
There's a Stackoverflow question on it, and other than a numpy solution (which is np.clip()), none of them appear to be as readable as your attempt to me.

I wasn't aware of it, but looks like a more common name for that function is clamp(), and some libraries might have an implementation, but not any in the standard library.
i like clamo better.