is there a single function to confine a number between two others? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: is there a single function to confine a number between two others? (/thread-31115.html) |
is there a single function to confine a number between two others? - Skaperen - Nov-24-2020 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. RE: is there a single function to confine a number between two others? - bowlofred - Nov-24-2020 You're asking if one number has a value between two others? I'd do that initially with the operators like lower <= n <= upperI'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) RE: is there a single function to confine a number between two others? - perfringo - Nov-24-2020 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 RE: is there a single function to confine a number between two others? - Skaperen - Nov-24-2020 this: def confine(a,n,b): n=max(n,a) n=min(n,b) return n RE: is there a single function to confine a number between two others? - bowlofred - Nov-24-2020 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. RE: is there a single function to confine a number between two others? - Skaperen - Nov-24-2020 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. RE: is there a single function to confine a number between two others? - bowlofred - Nov-24-2020 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.
RE: is there a single function to confine a number between two others? - Skaperen - Nov-28-2020 i like clamo better.
|