Compare Within Margin Using Python


The challenge

Create a function close_compare that accepts 3 parameters: ab, and an optional margin. The function should return whether a is lower than, close to, or higher than ba is “close to” b if margin is higher than or equal to the difference between a and b.

When a is lower than b, return -1.

When a is higher than b, return 1.

When a is close to b, return ``.

If margin is not given, treat it as zero.

Example: if a = 3b = 5 and the margin = 3, since a and b are no more than 3 apart, close_compare should return ``. Otherwise, if instead margin = 0a is lower than b and close_compare should return -1.

Assume: margin >= 0

Test cases

test.it("No margin")
test.assert_equals(close_compare(4, 5), -1)
test.assert_equals(close_compare(5, 5), 0)
test.assert_equals(close_compare(6, 5), 1)

test.it("With margin of 3")
test.assert_equals(close_compare(2, 5, 3), 0)
test.assert_equals(close_compare(5, 5, 3), 0)
test.assert_equals(close_compare(8, 5, 3), 0)
test.assert_equals(close_compare(8.1, 5, 3), 1)
test.assert_equals(close_compare(1.99, 5, 3), -1)

The solution in Python

Option 1:

def close_compare(a, b, margin = 0):
    return 0 if abs(a - b) <= margin else -1 if b > a else 1

Option 2:

def close_compare(a, b, margin=0):
    if a == b or abs(a - b) <= margin:
        return 0
    if a < b:
        return -1
    if a > b:
        return 1

Option 3 (using numpy):

from numpy import sign

def close_compare(a, b, margin=0):
    return abs(a-b) > margin and sign(a-b)