# 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) <= 1 or abs(a - c) <= 1:
if abs(c - a) >= 2 <= abs(c - b) or abs(b - a) >= 2 <= 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):
"""
>>> close_far(1, 2, 10)
True
>>> close_far(1, 2, 3)
False
>>> close_far(4, 1, 3)
True
"""
diff_ab = abs(a - b)
diff_ac = abs(a - c)
if diff_ab <= 1 or diff_ac <= 1:
diff_bc = abs(c - b)
return diff_ac >= 2 <= diff_bc or diff_ab >= 2 <= diff_bc
return False

• excellent tips, I learned a lot, replacing the innermost if with return is only valid because that particular if returned true or false isn't it? (in other words there was boolean comparison inside of it) – noob81 Jul 25 '15 at 19:28
• Replacing with return is valid because if the rest of the function: if the condition is not true, the function will return False anyway, so the outcome is exactly the same, but shorter to write. Technically, you could flatten the entire if, but that it would be overall less readable: return (abs(a - b) <= 1 or abs(a - c) <= 1) and abs(c - a) >= 2 <= abs(c - b) or abs(b - a) >= 2 <= abs(b - c) – Stop ongoing harm to Monica Jul 25 '15 at 19:47