簡體   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