How to find how many numbers are in q given range

Viewed 64

That's what I have tried:

def between(lst, a, b):
    for i in lst:
        count = 0
        if a < i < b:
            count+=1 
    return count 
3 Answers

The problem is you reset count to 0 for every element in the list.

def between(lst, a, b):
    count = 0
    for i in lst: 
        if a < i < b:
            count+=1 
    return count 

You can do this using len and a comprehension as well and not even have to have count to worry about:

def between(lst, a, b):
    return len(i for i in lst if a < i < b)

Your range validation needs to be inclusive. Try this:

def count_items_in_range(iterable: list, left_limit: float, right_limit: float) -> int:
    count: int = 0

    for item in iterable:
        if left_limit <= item <= right_limit:
            count+=1 

    return count 
Related