Reputation: 31
For example, if I have a value a = 4
and two input thresholds t1 = 3
and t2 = 5
.
a > t1
and a < t2
so the function func(a, t1, t2)
returns true.
But if I input t1 = 5
and t2 = 3
, even if a = 4
lies between the t1
and t2
, the function returns false. How to solve this?
So far I write this function in this way, but it only works when t1 < t2
. Is there some smart way to do this?
def func(a, t1, t2):
if a > t1 and a < t2:
return True
else:
return False
Upvotes: 0
Views: 807
Reputation: 23250
You could order the two thresholds before using them in the comparison with a
, for example by using the sorted
function:
smaller, larger = sorted([t1, t2])
If t1 <= t2
then smaller
will be t1
and larger
will be t2
, otherwise smaller
will be t2
and larger
will be t1
.
def func(a, t1, t2):
smaller, larger = sorted([t1, t2])
return smaller < a < larger
Upvotes: 0
Reputation: 13939
You can use or
:
def func(a, t1, t2):
return t1 < a < t2 or t2 < a < t1
print(func(4, 3, 5)) # True
print(func(4, 5, 3)) # True
print(func(4, 1, 2)) # False
Note that python allows chained comparisons so that you don't need to write t1 < a and a < t2
. Also, you don't need the redundant if
statement as in:
if t1 < a < t2 or t2 < a < t1:
return True
else:
return False
Upvotes: 1