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
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
Works with floating point numbers. Ex 1 and 1.4 will fail in original code but succeed in this.
Easy to change the definition of "is close to". Ex, can use 0.5 or 10000000 on the rhs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With