Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value is between pair of values in a tuple?

Is there an efficient way (nice syntax) to check if a value is between two values contained in a tuple?

The best thing I could come up with is:

t = (1, 2)
val = 1.5
if t[0] <= val <= t[1]:
    # do something

Is there a nicer way to write the conditional?

like image 522
Nat Dempkowski Avatar asked Feb 14 '14 16:02

Nat Dempkowski


2 Answers

No, there is no dedicated syntax, using chained comparisons is the right way to do this already.

The one 'nicety' I can offer is to use tuple unpacking first, but that's just readability icing here:

low, high = t
if low <= val <= high:

If you are using a tuple subclass produced by collection.namedtuple() you could of course also use the attributes here:

from collections import namedtuple

range_tuple = namedtuple('range_tuple', 'low high')
t = range_tuple(1, 2)

if t.low <= val <= t.high:
like image 124
Martijn Pieters Avatar answered Oct 21 '22 08:10

Martijn Pieters


You could make your own sugar:

class MyTuple(tuple):

    def between(self, other):
        # returns True if other is between the values of tuple 
        # regardless of order
        return min(self) < other < max(self)

        # or if you want False for MyTuple([2,1]).between(1.5)
        # return self[0] < other < self[1]

mt=MyTuple([1,2])    
print mt.between(1.5)
# True
like image 1
dawg Avatar answered Oct 21 '22 09:10

dawg