if number is 1-2, 4 or 6-8 or 12-28, 30, 32...

Cliff Wells logiplexsoftware at earthlink.net
Mon Jun 10 17:59:30 EDT 2002


On Mon, 10 Jun 2002 21:25:06 +0000 (UTC)
Gustaf Liljegren wrote:

> I'm making a function that takes one integer and returns a boolean that 
> says if the integer matches a number in a certain group of numbers. This 
> group consists of single numbers aswell as ranges spanning thousands of 
> numbers. I'm looking for an elegant way to write this function.

def isin(n, ranges):
    for r in ranges:
        try: 
            s, e = r
            if s <= n <= e:
                return 1
        except TypeError:
            if n == r:
                return 1
    return 0

ranges = [(1, 999), 1004, 1006, (1050, 2000)]

print isin(0, ranges)
print isin(1, ranges)
print isin(2, ranges)
print isin(1000, ranges)
print isin(1999, ranges)

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





More information about the Python-list mailing list