How to apply max & min boundaries to a value without using conditional statements

前端 未结 9 1779
滥情空心
滥情空心 2021-02-10 11:01

Problem:

Write a Python function, clip(lo, x, hi) that returns lo if x is less than lo; hi if x is greater than hi; and x otherwise. For this problem, y

相关标签:
9条回答
  • 2021-02-10 11:25
    def clip(lo, x, hi):
        return sorted((lo, x, hi))[1]
    
    0 讨论(0)
  • 2021-02-10 11:28

    This will do the trick without conditional operators.

    max(lo,min(hi,x))
    
    0 讨论(0)
  • 2021-02-10 11:31

    min? max? What about:

    def clip(lo,x,hi):
        return (lo,(hi,x)[x<hi])[x>lo]
    
    0 讨论(0)
  • 2021-02-10 11:32

    Without giving out the whole solution - you don't need to "check" anything. A value limited to lo from the bottom is what you get from running max(x, lo).

    Also value clipped to one boundary is not going to be affected by clipping to the other boundary, so you can safely run the result of one correction through another one.

    0 讨论(0)
  • 2021-02-10 11:35

    here is also a solution: return min(max(x, lo), hi)

    0 讨论(0)
  • 2021-02-10 11:36

    Another solution:

    def clip(lo, x, hi):
        result = {x: x}
        result[min(x, lo)] = lo
        result[max(x, hi)] = hi
        return result[x]
    
    0 讨论(0)
提交回复
热议问题