Skip to main content
 首页 » 编程设计

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

2025年05月04日14mengfanrong

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 小于 low,max() 将返回 low。否则它将返回 x。

现在您已经从两个中得到较大的一个,您需要使用 x = min(high, x) 从新的 x 中得到较小的一个> 和 高。

合并后,您将获得:

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))