[英]What is the logic behind this algorithm?
這個問題的解釋可以在@http ://www.cemc.uwaterloo.ca/contests/computing/2017/stage%201/juniorEF.pdf
(這是題為“完全電氣化”的第三個問題)。
def electrical(a,b,c,d,e) :
charge = e
x_dif = abs(c - a)
y_dif = abs(d - b)
total_dif = (x_dif + y_dif)
if (((total_dif) == charge) or ((total_dif % 2 == 0) and (charge %2 == 0)) or ((total_dif % 2 != 0) and (charge % 2 !=0))) :
return "Y"
else :
return "N"
print(electrical(10,2,10,4,5))
此代碼也可以在https://repl.it/@erichasegawa/2017-CCC-Junior-S3找到。
我正在學習編寫本周的加拿大計算機比賽,我對他們的一種算法有疑問; 當電荷和距離都是偶數或不均勻時,為什么我的函數會返回“Y”,但是如果一個是偶數而另一個不是(反之亦然),它會返回 false。 我知道這是有效的,但我不知道它為什么或如何工作。 如果有人可以解釋這一點,那就太好了。
分解條件:
if (((total_dif) == charge) or ((total_dif % 2 == 0) and (charge %2 == 0)) or ((total_dif % 2 != 0) and (charge % 2 !=0)))
我們有...
(total dif == charge) # they are equal, so either both odd or even
or ((total_dif % 2 == 0) and (charge % 2 == 0)) # if their remainder after division by 2 is 0, then they're both even
or ((total_dif % 2 != 0) and (charge % 2 != 0)) # if their remainder after division by 2 is NOT 0, then they're both odd
請注意,第一個條件是不必要的; 我們已經檢查了兩者是偶數還是奇數。 擁有或刪除不應該改變程序的行為。
另請注意,“total_dif”周圍的括號集是不必要的,並且會使已經很大的條件更難以閱讀。 事實上,你應該把表達式拆分成不同的部分,也許作為變量both_even 和both_odd,然后檢查
if (both_even or both_odd)
這更具可讀性
您的代碼說明
if (((total_dif) == charge) or ((total_dif % 2 == 0) and (charge %2 == 0)) or ((total_dif % 2 != 0) and (charge % 2 !=0))) :
第一個條件
(total_dif == charge)
正在確定電荷是否等於所需的距離,因此兩者都是偶數或奇數。
第二個條件
((total_dif % 2 == 0) and (charge %2 == 0))
檢查兩個參數(電荷和距離)除以 2 的余數是否為偶數(% 運算符); 它正在檢查它們是否都是偶數。
你的第三個條件正好相反,它檢查它們是否都是奇數。
從本質上講,您的條件是檢查電荷和距離之間的差值是否可以被 2 整除,因為您可以進行兩次掉頭以抵消這個偶數盈余。
因此,您的條件可以簡化為
if ((charge-total_dif) % 2 == 0):
你的問題在技術上與問題無關,因為如果一個參數是偶數而另一個是奇數,那么你要么有盈余,要么有赤字。 總是。
您的代碼唯一的另一個問題是它從不檢查電荷是否大於或等於距離!
這意味着你可以有一個偶數距離 n(如 28321728932),電荷為 0,但仍返回“Y”,或者具有奇數距離 x(如 3121),電荷為 3,但仍返回“Y”。
因此,您應該包括條件
charge >= total_dif
在你的代碼中。
總之,你的情況應該是
if ((charge >= total_dif) and ((charge-total_dif) % 2 == 0):
最后注意:請使用較短的變量名稱。 在像您這樣的短程序中,區分較短的名稱不會有困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.