Given a list, print the number of numbers in the given range.
Examples:
Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 40-80 Output : 6 Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40 Output : 4Multiple Line Approach:
Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter. At the end of traversal, the value of the counter will be the answer for the number of
numbers in specified range.
Below is the Python implementation of the above approach
Python
def count(list1, l, r):
c = 0
for x in list1:
if x>= l and x<= r:
c+= 1
return c
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
print count(list1, l, r)
Single Line Approach:
We can write a single line for traversal and checking condition together:
The return value(true) of the
condition check is stored in a list, and at the end the length of the list returns the answer.
Below is the Python implementation of the above approach
Python
def count(list1, l, r):
return len(list(x for x in list1 if l <= x <= r))
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
print count(list1, l, r)
Approach#3 : Using sum We can use sum in this problem. We use list comprehension to iterate over the list and check number is in range or not if it is present comparison will have 1 as have else 0 as value. Sum function return the sum of total of parameters.
Python3
def count(list1, l, r):
return sum( l <= x <= r for x in list1)
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
print( count( list1, l, r ) )
Using the built-in function filter():
This function takes a function and an iterable as arguments and returns a new iterable containing only the elements for which the function returns True.
To count the number of numbers in the given range, we can define a lambda function that checks if a number is in the range, and then pass this function to filter() along with the list. The length of the resulting iterable will be the number of numbers in the range.
Here is an example of how to use this approach:
Python3
def count(list1, l, r):
return len(list(filter(lambda x: l <= x <= r, list1)))
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
print(count(list1, l, r))
This will output 6, as in the other solutions.
The time complexity of this approach is O(n), where n is the length of the list, and the space complexity is O(n), since filter() creates a new iterable containing all the elements that satisfy the condition.