def near_extremes(x, a, b, r):
    """checks if x is within r of a or b, and between them"""
    assert a <= b
    if x >= a and x <= b:
        if x - a < r or b - x < r:
            return True
    return False