8

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
lowZoom
  • 133
  • 1
  • 4

2 Answers2

9

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
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
2

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

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73