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

Usr*_*Dev 1 python max min

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
    '''
Run Code Online (Sandbox Code Playgroud)

Mar*_*nen 6

使用x = max(low, x)以获得更大的一个了两部; 如果x小于low,max()将返回low.否则它会回来x.

现在你从两个中获得了更大的一个,你需要使用x = min(high, x)从新的x和更小的一个high.

合并后,您将获得:

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

哪些可以进一步缩短为:

def clip(low, x, high):
    return min(high, max(low, x))
Run Code Online (Sandbox Code Playgroud)