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.

defcheck_list(li):
    returnall((type(i) == intand1 < i < 6for 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:

defcheckList(aList):
   returnall(isinstance(i, int)  and1 < i < 6for 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.

defcheckList(aList):
    for i in aList:
        ifnotisinstance(i, int):
             returnFalseif i < 2:
            returnFalseif i > 5:
            returnFalsereturnTrue# 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:

defcheckList(aList):
    for i in aList:
        ifnotisinstance(i, int):
             returnFalseif2 > i > 5:
            returnFalsereturnTrue

Solution 3:

This will work for you

defcheck_sequence(sequence, low, high):
    ifall(isinstance(i, int) for i in sequence):
        returnall(low < i < high for i in sequence)
    else:
        returnFalseprint(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:

defcheckList(seq):
    filtered = filter(seq, lambda x: 1 < int(x) < 6)
    returnlen(filteted) == len(seq)

Post a Comment for "List With Multiple Conditions"