Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a number is between two values, which can be given in any order

Tags:

python

>>> r = range(4, -1)
>>> 3 in r
False
>>> q = range(-1, 4)
>>> 3 in q
True

I have the same bounds, -1 and 4, and the same test value, so how do I say that '3' is between '-1' and '4' when I do not know the order that they are given to me in?

like image 435
Tanishq dubey Avatar asked Nov 03 '25 15:11

Tanishq dubey


2 Answers

Why not sort the bounds first?

r = range(*sorted((4, -1)))
q = range(*sorted((-1, 4)))
like image 100
John La Rooy Avatar answered Nov 06 '25 06:11

John La Rooy


range doesn't do what you think it does.

It creates a list; it's not a numeric range (edit: actually it does in Python 3).

Just imagine a case, when the lowerEnd is -20000 and the upperEnd is +20000. Using the range( -20000, 20000 ) and comparing num in such a range() is a waste of both memory and CPU-power.

It is quite enough to compare a num against lowerEnd & upperEnd limit

You want to check:

num = 3
print(-1 < num < 4)
like image 42
101 Avatar answered Nov 06 '25 05:11

101