假设我有一个数字变量,它将添加另一个值,但我想确保该变量永远不会超过最大值,并且一旦超过,将简单地默认为最大值。
例如,给定最大值 100,以及执行此操作的函数,该函数称为maxadd:
input1 = 90
input2 = 8
maxadd(input1, input2, 100)
>>> 98
input1 = 95
input2 = 8
maxadd(input1, input2, 100)
>>> 100
Run Code Online (Sandbox Code Playgroud)
我可以将它定义为这样的普通函数:
def maxadd(a, b, _max):
res = a + b
if res > _max:
return _max
return res
Run Code Online (Sandbox Code Playgroud)
但我觉得它可以在一行中完成,也许可以使用 lambda。我似乎无法弄清楚什么。性能也是一个问题,所以我想要最快的解决方案,我觉得这个功能可能会采取不必要的步骤
从逻辑上讲,您希望返回a + b或_max,以较小者为准。因此,您可以min为此使用内置函数:
def maxadd(a, b, _max):
return min(a + b, _max)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61 次 |
| 最近记录: |