Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in function to keep a number in certain range in python? [duplicate]

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
like image 887
lowZoom Avatar asked Dec 18 '13 07:12

lowZoom


People also ask

How do you specify a range in Python?

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.

What does range () do in Python?

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.

Does range () return a list?

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.

What a range () function does give an example?

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.


2 Answers

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
like image 124
inspectorG4dget Avatar answered Oct 08 '22 11:10

inspectorG4dget


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

like image 36
Steve Barnes Avatar answered Oct 08 '22 11:10

Steve Barnes