【问题标题】:Alternative approaches to comparing values比较值的替代方法
【发布时间】:2019-04-13 03:30:50
【问题描述】:

我正在尝试 CodingBat 的这个问题

给定三个整数,a b c,如果 b 或 c 之一是“关闭”(不同 最多 1),而另一个是“远”,与其他两个值相差 2 或 更多的。注意:abs(num) 计算一个数字的绝对值。

close_far(1, 2, 10) → True
close_far(1, 2, 3) → False
close_far(4, 1, 3) → True 

我知道我可以通过一系列 if else 语句来解决这个问题,但它真的很长,还有其他方法可以解决这个问题吗???

【问题讨论】:

  • 你能发布你的尝试吗?
  • 注:在问题描述中是一个很好的线索。

标签: python algorithm


【解决方案1】:

这个问题可以通过排序大大简化,不失一般性:

def close_far(a, b, c):
  x, y, z = sorted([a, b, c])
  delta_close, delta_far = sorted([y - x, z - y])
  return delta_close <= 1 and delta_far >= 2

【讨论】:

    【解决方案2】:
    def close_far(a, b, c):
        def close(x, y): return abs(x - y) <= 1
        def far(x, y): return abs(x - y) >= 2
        return (close(b, a) and far(c, a) and far(c, b) or
                close(c, a) and far(b, a) and far(b, c))
    
    >>> close_far(1, 2, 10)
    True
    >>> close_far(1, 2, 3)
    False
    >>> close_far(4, 1, 3)
    True
    

    【讨论】:

    • 使用显式括号对 sndor 运算符进行分组可能会更好,当然它是正确的。
    • @user2284926 我敦促您看看 wim 的方法,它更具适应性
    【解决方案3】:

    一点帮助:

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

    【讨论】:

      【解决方案4】:

      这是一种方法:

      def close_far(a, b, c):
          return not ((is_close(a,b)==is_close(a,c)) or is_close(b,c))
      
      
      def is_close(num1, num2):
          return abs(num1-num2)<=1
      

      【讨论】:

        猜你喜欢
        • 2020-05-29
        • 2017-10-05
        • 1970-01-01
        • 2013-12-30
        • 2017-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多