Skip to content

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"No margin") test.assert_equals(close_compare(4, 5), -1) test.assert_equals(close_compare(5, 5), ) test.assert_equals(close_compare(6, 5), 1)"With margin of 3") test.assert_equals(close_compare(2, 5, 3), ) test.assert_equals(close_compare(5, 5, 3), ) test.assert_equals(close_compare(8, 5, 3), ) test.assert_equals(close_compare(8.1, 5, 3), 1) test.assert_equals(close_compare(1.99, 5, 3), -1)
Code language: Python (python)

The solution in Python

Option 1:

def close_compare(a, b, margin = ): return if abs(a - b) <= margin else -1 if b > a else 1
Code language: Python (python)

Option 2:

def close_compare(a, b, margin=): if a == b or abs(a - b) <= margin: return if a < b: return -1 if a > b: return 1
Code language: Python (python)

Option 3 (using numpy):

from numpy import sign def close_compare(a, b, margin=): return abs(a-b) > margin and sign(a-b)
Code language: Python (python)

See also  Multiprocessing in Python3
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x