1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 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) \$\endgroup\$ – noob81 Jul 25 '15 at 19:28
  • \$\begingroup\$ 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) \$\endgroup\$ – Stop ongoing harm to Monica Jul 25 '15 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.