Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if 2 given number are close to each other python

Tags:

python

i have been asked to make code that doesen't have loops and check if first number is close to second number (close means bigger or smaller by one).I tried using huge conditions but i wodered maybe there is an easyer way then do things like this:

if num1 == num2 or num1 == num2 - 1 or num1 == num2 + 1

like image 492
raz erez Avatar asked Oct 24 '25 23:10

raz erez


2 Answers

Calculate the difference between the 2 numbers, take the absolute value of that (in case num2 is larger than num1) and compare the result to 1:

abs(num1 - num2) <= 1

The advantage of this over OP's code

  1. Works with floating point numbers. Ex 1 and 1.4 will fail in original code but succeed in this.

  2. Easy to change the definition of "is close to". Ex, can use 0.5 or 10000000 on the rhs.

like image 139
Johnny Mopp Avatar answered Oct 27 '25 14:10

Johnny Mopp


Didn't see this as a solution, so I'm adding it.

Using the math.isclose() method introduced in Python 3.5 with PEP 458:

#Function signature defined as
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)

Therefore:

math.isclose(a,b,rel_tol=1)

Although this is a bit overkill for OP's exact use case, this is the most pythonic way of performing the check. Also, according to the documentation, this can handle NaN and +/- inf values.

The IEEE 754 special values of NaN, inf, and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN. inf and -inf are only considered close to themselves.

like image 44
blackbrandt Avatar answered Oct 27 '25 14:10

blackbrandt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!