如何使用 min 和 max 函数解决这个问题,但没有条件语句

how to resolve this using min and max functions but no conditional statements

def clip(lo, x, hi):
    '''
    Takes in three numbers and returns a value based on the value of x.
    Returns:
     - lo, when x < lo
     - hi, when x > hi
     - x, otherwise
    '''

使用x = max(low, x)从两个中取出较大的一个;如果 x 小于 lowmax() 将 return low。否则它将 return x.

既然你得到了两个中较大的一个,你需要使用x = min(high, x)从新的xhigh中得到较小的一个。

合并后,您将得到:

def clip(low, x, high):  # Why not use full names?
    x = max(low, x)
    x = min(high, x)
    return x

可以进一步缩短为:

def clip(low, x, high):
    return min(high, max(low, x))