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

前端 未结 9 1900
滥情空心
滥情空心 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:42

    Here is a solution, assuming that lo < hi.

    def clip(lo, x, hi):
        return max(lo, min(hi, x))
    

    How it works in each case:

    • lo, when x < lo: if lo < hi, then x < hi, so min(hi, x) returns x and max(lo, x) returns lo.
    • hi, when x > hi: min(hi, x) returns hi and if lo < hi, max(lo, hi) returns hi
    • x, otherwise: x > lo and x < hi, so min(hi, x) returns x and max(lo, x) returns x

提交回复
热议问题