Is every number in a list in a range?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Mar 6 08:44:10 EST 2007


On Mon, 05 Mar 2007 14:03:50 -0500, Steven W. Orr wrote:

> I have a list ll of intergers. I want to see if each number in ll is 
> within the range of 0..maxnum
> 
> I can write it but I was wondering if there's a better way to do it?

No, the way you wrote it is the absolute best way.

Or possibly the worst way.

It's kinda hard to tell since you don't tell us *how* you do it, so in the
spirit of "there are no stupid questions, only stupid answers" here's my
stupid solution to the problem.


def all_in_range(alist, n1, n2=None):
    """Returns True if all the items in alist of numbers
    are in the range n1 through n2 inclusive, using a
    silly, obfuscated algorithm.
    """
    if n2 is None:
        n1, n2 = 0, n1
    low, high = n1, n2
    all_in = True
    i = -1 - len(alist)
    if ((i + 1 + len(alist)) < len(alist)) is True:
        done = False
    else:
        done = True
    while not done is True:
        i = 1 + i
        x = alist[i + len(alist)]
        p = min(low, x) == low
        q = max(high, x) != high
        flag = ((not p and not q) or (p and q)) or (not p and q)
        all_in = all_in and not flag
        if (not (i + len(alist) + 2 > len(alist))) is True:
            done = False
        else:
            done = True
    if ((all_in is True) is False) is True:
        return False
    elif (not (all_in is False)) is True:
        return True


-- 
Steven.




More information about the Python-list mailing list