【问题标题】:What is the logic behind this algorithm?这个算法背后的逻辑是什么?
【发布时间】:2018-02-12 00:19:46
【问题描述】:

这个问题的解释可以看@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。我知道这行得通,但我不知道为什么或如何 行得通。如果有人可以解释这一点,那就太好了。

【问题讨论】:

标签: python python-3.x algorithm graph modulus


【解决方案1】:

分解条件:

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)

可读性更强

【讨论】:

    【解决方案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 整除,因为您可以进行两次 U 形转弯来抵消这个偶数盈余。

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

    if ((charge-total_dif) % 2 == 0):
    

    从技术上讲,您的问题与问题无关,因为如果一个参数是偶数而另一个是奇数,那么您将要么有盈余,要么有赤字。总是。

    您的代码唯一的另一个问题是它从不检查电荷是否大于或等于距离

    这意味着你可以有一个偶数距离 n(如 28321728932),但仍返回 'Y',或者有一个奇数距离 x(如 3121),有 3 个电荷,仍然返回'Y'。

    因此,您应该包含条件

    charge >= total_dif
    

    在您的代码中。

    总的来说,你的情况应该是

    if ((charge >= total_dif) and ((charge-total_dif) % 2 == 0):
    

    最后提示:请使用较短的变量名。在像您这样的短程序中,您不会有区分较短名称的困难。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多