Using logic to compare absolute values Is there a way to make my code simpler/more Pythonic?


  Given three int values (a, b, c), return True if one of b or c is "close"
  (differing from a by at most 1), while the other is "far", differing
  from both other values by 2 or more. Note: abs(num) computes the
  absolute value of a number. 
  
  close_far(1, 2, 10) → True
  close_far(1, 2, 3) → False
  close_far(4, 1, 3) → True


def close_far(a, b, c):
    if abs(a - b) &lt;= 1 or abs(a - c) &lt;= 1:
        if abs(c - a) &gt;= 2 &lt;= abs(c - b) or abs(b - a) &gt;= 2 &lt;= abs(b - c):
            return True       
    return False
Some tips:


You could replace the innermost if with return
Adding doctests would be nice
Note that abs(a - b) is the same as abs(b - a). To avoid repeated calculation of abs values, it would be more optimal to cache in local variables


Like this:

def close_far(a, b, c):
    """
    &gt;&gt;&gt; close_far(1, 2, 10)
    True
    &gt;&gt;&gt; close_far(1, 2, 3)
    False
    &gt;&gt;&gt; close_far(4, 1, 3)
    True
    """
    diff_ab = abs(a - b)
    diff_ac = abs(a - c)
    if diff_ab &lt;= 1 or diff_ac &lt;= 1:
        diff_bc = abs(c - b)
        return diff_ac &gt;= 2 &lt;= diff_bc or diff_ab &gt;= 2 &lt;= diff_bc
    return False