Compare within Margin using Python

1 min read 243 words

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags