Does something like this exist in python library?
def func(num, start, end):
if num <= start:
return start
if num >= end:
return end
return num
Syntax of Python range() function start: [ optional ] start value of the sequence. stop: next value after the end value of the sequence. step: [ optional ] integer value, denoting the difference between any two numbers in the sequence.
Python range() Function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
The range() function, on the other hand, returns a list or sequence of numbers and consumes more memory than xrange() . Since the range() function only stores the start, stop, and step values, it consumes less amount of memory irrespective of the range it represents when compared to a list or tuple.
The range() is an in-built function in Python. It returns a sequence of numbers starting from zero and increment by 1 by default and stops before the given number. It has three parameters, in which two are optional: start: It's an optional parameter used to define the starting point of the sequence.
min
and max
approach
def func(num, start, end):
return min(max(num, start), end)
Or the ternary approach
def func(num, start, end):
return num if start<num<end else start if num<=start else end
The closest I can come up with is:
def func(num, start, end):
return min(max(start,num),end)
But given some of the people that I work with better might be:
def func(num, start, end):
""" Clip a single value """
top, bottom = max(start, end), min(start, end)
return min(max(bottom,num),top)
But if you have several values in an array there is always numpy.clip
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With