check if 2 given number are close to each other python

Issue

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

Solution

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.

Answered By – Johnny Mopp

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published