Skip to content Skip to sidebar Skip to footer

List With Multiple Conditions

I am creating a boolean function that checks if each element in my list is greater than 1 and less than 6. Also the list is positive integers and not negative, 0, string or anythin

Solution 1:

Use a generator expression to build an intermediate list of elements, then check them against all to see if they fit in your constraints.

def check_list(li):
    return all((type(i) == int and 1 < i < 6 for i in li))

Solution 2:

A single generator expression with all using isinstance(i, int) to check is each element is an int and 1 <= i <= 6 to make sure each int is in the range 1-6:

def checkList(aList):
   return all(isinstance(i, int)  and 1 < i < 6 for i in aList)

all will short circuit and return False for any non int or any value less than 1 or greater the 5 or return True if all the elements are ints and in the range 1-6.

In your own code you are checking for if i < 1 and elif i > 6 when you say you want to check if each element in my list is greater than 1 and less than 6 so it would be if i < 2 and elif i > 5 return False, 1 is not less than 1 and 6 is greater than 5, so to correct your own logic and to check for ints.

def checkList(aList):
    for i in aList:
        if not isinstance(i, int):
             return False
        if i < 2:
            return False
        if i > 5:
            return False
    return True # outside loop

You need to move the return True outside loop, just because one is an int between 1 - 6 does not mean they all are.

Which could be rewritten as:

def checkList(aList):
    for i in aList:
        if not isinstance(i, int):
             return False
        if 2 > i > 5:
            return False              
    return True

Solution 3:

This will work for you

def check_sequence(sequence, low, high):
    if all(isinstance(i, int) for i in sequence):
        return all(low < i < high for i in sequence)
    else:
        return False
print(check_sequence([2, 5, 4, 3, 3], 1, 6))
>> True

The important concept here is low < i < high. In Python, you can specify a range of values that the variable should be between.


Solution 4:

You could just use filter it would go something like this

filtered = filter(seq, lambda x: 1 < int(x) < 6)

That will return a filtered list containing only items which were between 1 and 6. You can then check if the list has the same length to see if anything was removed.

Going this route, your function would look like this:

def checkList(seq):
    filtered = filter(seq, lambda x: 1 < int(x) < 6)
    return len(filteted) == len(seq)

Post a Comment for "List With Multiple Conditions"