这个算法背后的逻辑是什么?

2024-04-26 22:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题的解释可以在@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。我知道这是可行的,但我不知道它为什么或者如何起作用。如果有人能解释这一点那就太好了。你知道吗


Tags: orandhttpreturnwwwabselectricalca
2条回答

您的代码状态

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整除,因为你可以做两个U形转弯来抵消这个均匀的剩余。你知道吗

因此,你的条件可以简化为

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):

最后注意:请使用较短的变量名。在像你这样的短程序中,你不会有区分短名字的困难。你知道吗

分解条件:

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”周围的一组括号是不必要的,这使得已经很庞大的条件更难阅读。事实上,您应该将表达式分成不同的部分,也许作为变量同时包含偶数和奇数,然后进行检查

if (both_even or both_odd)

更具可读性

相关问题 更多 >