[英]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
,而是使用min
和max
。
用英語重新表述,如果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 語句?
編輯:
對這個問題的評論/答案幫助我意識到我原來的簡單英語重新表述並不是思考問題的好方法。 考慮它的更好方法是確定哪個論點介於其他兩個論點之間。
一行代碼:
#! 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.