0

i have a simple problem in Python where i need to return a value that is equal to floor if it is smaller than floor, and return ceiling if the value is larger than ceiling. I'm not sure if there is a simpler way to do so. What i will do is:

def floor_ceil(x):
    floor = 0
    ceil = 100
    if x < floor:
       return floor
    elif x > ceil:
       return ceil
    return x

Are there simpler ways to do so? The code looks clunky

bryan.blackbee
  • 1,934
  • 4
  • 32
  • 46
  • "if it is smaller than floor," ... "if the value is larger than ceiling": I don't think that is ever the case, by definition. – 9769953 Dec 03 '18 at 08:24
  • But from your function, you'd want a clip- or clamp-style function. What you have is currently fine. – 9769953 Dec 03 '18 at 08:25
  • You could consider `def floor_ceil(x, floor=0, ceil=100):` as to make your function more generic. – 9769953 Dec 03 '18 at 08:26
  • Also: https://stackoverflow.com/questions/9775731/clamping-floating-numbers-in-python – 9769953 Dec 03 '18 at 08:26
  • Also worth mentioning [`numpy.clip`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.clip.html) – DeepSpace Dec 03 '18 at 08:28

1 Answers1

0

You could reuse the built-in max and min:

def floor_ceil(x):
    return max(0, min(100, x))
Mureinik
  • 297,002
  • 52
  • 306
  • 350