繁体   English   中英

if/elif/else 如何用 min() 和 max() 替换?

[英]How can if/elif/else be replaced with min() and max()?

使用MIT 的 OpenCourseWare 6.01SC进行练习。 问题 3.1.5:

定义一个函数clip(lo, x, hi)该返回lo如果x小于lo ,返回hi如果x大于hi ,并且返回x否则。 您可以假设lo < hi ...不要使用if ,而是使用minmax

用英语重新表述,如果x是参数中最少的,则返回lo 如果x是最大的参数,则返回hi 否则,返回x 因此:

def clip(lo, x, hi):
    if min(lo, x, hi) == x:
        return lo
    elif max(lo, x, hi) == x:
        return hi
    else:
        return x

也许我没有正确理解问题,但我无法弄清楚如何在不使用if情况下返回结果。 如何修改函数以删除 if/elif/else 语句?

链接到原始问题 3.1.5

链接到上一个问题 3.1.4(用于上下文)

编辑:

对这个问题的评论/答案帮助我意识到我原来的简单英语重新表述并不是思考问题的好方法。 考虑它的更好方法是确定哪个论点介于其他两个论点之间。

一行代码:

#! python3.8

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

print(clip(1, 2, 3))
print(clip(2, 1, 3))
print(clip(1, 3, 2))

# Output
# 2
# 2
# 2

你可以返回这个公式:

x + lo + hi - max(x, lo, hi) - min(x, lo, hi)

个案论证:

情况1:

If min(lo, x, hi) = lo and max(lo, x, hi) = hi
  x + lo + hi - max(x, lo, hi) - min(x, lo, hi) ==> x + lo + hi - hi - lo ==> x

案例2:

If min(lo, x, hi) = lo and max(lo, x, hi) = x
  x + lo + hi - max(x, lo, hi) - min(x, lo, hi) ==> x + lo + hi - x - lo ==> hi

案例3:

If min(lo, x, hi) = x and max(lo, x, hi) = hi
  x + lo + hi - max(x, lo, hi) - min(x, lo, hi) ==> x + lo + hi - hi - x ==> lo

该公式返回所有可能情况下的预期答案。

给你,一个完全不使用 if-else 的值检查函数。 虽然块只会运行一次,所以没有冗余。

def clip(lo, x, hi):
    low = (min(lo, x) == x)
    high = (max(x, hi) == x)
    while low:
        return lo
    while high:
        return hi
    return x
    

编辑:我不知道他为什么不赞成我的代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM