简体   繁体   English

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

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

Working on an exercise from MIT's OpenCourseWare 6.01SC .使用MIT 的 OpenCourseWare 6.01SC进行练习。 Problem 3.1.5:问题 3.1.5:

Define a function clip(lo, x, hi) that returns lo if x is less than lo , returns hi if x is greater than hi , and returns x otherwise.定义一个函数clip(lo, x, hi)该返回lo如果x小于lo ,返回hi如果x大于hi ,并且返回x否则。 You can assume that lo < hi .您可以假设lo < hi ...don't use if , but use min and max . ...不要使用if ,而是使用minmax

Reformulated in English, if x is the least of the arguments, return lo ;用英语重新表述,如果x是参数中最少的,则返回lo if x is the greatest of the arguments, return hi ;如果x是最大的参数,则返回hi otherwise, return x .否则,返回x Thus:因此:

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

Maybe I am not understanding the problem correctly, but I can't figure out how to return a result without using if at all.也许我没有正确理解问题,但我无法弄清楚如何在不使用if情况下返回结果。 How can the function be modified to remove the if/elif/else statements?如何修改函数以删除 if/elif/else 语句?

Link to original problem 3.1.5 链接到原始问题 3.1.5

Link to previous problem 3.1.4 (for context) 链接到上一个问题 3.1.4(用于上下文)

EDIT:编辑:

Comments/answers to this question helped me realize that my original plain English reformulation wasn't a great way to think about the problem.对这个问题的评论/答案帮助我意识到我原来的简单英语重新表述并不是思考问题的好方法。 A better way to think about it would have been to determine which of the arguments is between the other two.考虑它的更好方法是确定哪个论点介于其他两个论点之间。

One line of code:一行代码:

#! 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

You can return this formula:你可以返回这个公式:

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

Arguing by cases:个案论证:

Case 1:情况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

Case 2:案例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

Case 3:案例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

The formula returns the expected answer on all possible cases.该公式返回所有可能情况下的预期答案。

Here you go, a value checking function without using if-else at all.给你,一个完全不使用 if-else 的值检查函数。 While block will only run for once so there is no redundancy.虽然块只会运行一次,所以没有冗余。

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
    

EDIT: I don't know why he downvoted my code编辑:我不知道他为什么不赞成我的代码

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

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