codingbat 问题:close_far |仅通过一项测试 |嘻嘻

问题描述 投票:0回答:3

练习: 给定三个整数 a b c,如果 b 或 c 之一是“接近”(与 a 最多相差 1),而另一个是“远”,与其他值相差 2 或更多,则返回 True。注意:abs(num) 计算数字的绝对值。

https://codingbat.com/prob/p160533

我的代码:

def close_far(a, b, c):
  if (b == a + 1 or a - 1 or a) or (c == a + 1 or a - 1 or a):        #looking for the "close" one
    if (c > a + 2 and b + 2) or (c <= a - 2 and b - 2):               #looking for c to be the "far" one
        return True
    elif (b > (a + 2 and c + 2)) or (b <= (a - 2 and c - 2)):         #looking for b to be the "far" one
        return True
    else:    
      return False

错误答案 -> close_far(4, 3, 5) → False True X

我的代码给出了 True,尽管它是 False。


我实际上不知道我做错了什么。我猜我的第二个 if 语句有问题......括号?或/和? 感谢任何帮助!

screenshot

python if-statement logic
3个回答
1
投票

嗯,我猜对了!我弄乱了 elif 语句中的括号,导致测试失败。你让我走上了正轨约翰尼·莫普,谢谢你的帮助。

def close_far(a, b, c):
  if (b == a + 1 or a - 1 or a) or (c == a + 1 or a - 1 or a):              #looking for the "close" one
    if ((c > a + 2) and (c > b + 2)) or ((c <= a - 2) and (c <= b - 2)):    #looking for c to be the "far" one
        return True
    elif (b > (a + 2 and c + 2)) or ((b <= a - 2) and (b <= c - 2)):        #looking for b to be the "far" one
        return True
    else:    
      return False

1
投票

尝试了简单的 OR 、 AND 运算。对我来说很好用。

def close_far(a, b, c):
  if abs(b-c)>=2:
    if (abs(a-b)<=1 and abs(a-c)>=2) or ( abs(a-c)<=1 and abs(a-b)>=2):
      return True
  return False

0
投票
def close_far(a, b, c):

  close_b = close(b, a) 
  close_c = close(c, a)

  far_b = far(b, a) and far(b, c)
  far_c = far(c, a) and far(c, b)
  
  return close_b and far_c or close_c and far_b
  
  
  
def close(a, b):
  
  if (abs(a-b)) < 2:
    return True
  else:
    return False

def far(a, b):
  
  if (abs(a - b)) > 1:
    return True
  else:
    return False

我发现将复杂的逻辑结构分解为单独的函数更容易。首先创建 close 和 far 函数,然后验证输出场景。

close 函数检查给定的两个输入是否相差“最多一个”。 far 函数检查给定的两个输入是否相差“两个或更多”。

最终验证问题描述的案例:

  1. 如果“b”靠近“a”,请检查“c”是否远离“a”和“b”。
  2. 如果“c”靠近“a”,请检查“b”是否远离“a”和“c”。
© www.soinside.com 2019 - 2024. All rights reserved.