Python | Remove all sublists outside the given range
Given, list of lists and a range, the task is to traverse each sub-list and remove sublists containing elements falling out of given range. Examples:
Input :
left= 10, right = 17, list = [[0, 1.2, 3.4, 18.1, 10.1],
[10.3, 12.4, 15, 17, 16, 11],
[100, 10, 9.2, 11, 13, 17.1], ]
Output: [[10.3, 12.4, 15, 17, 16, 11]]
Input :
left= 1, right = 9, list = [[11, 12, 15, 17, 3],
[3, 1, 4, 5.2, 9, 19],
[2, 4, 6, 7.2, 8.9]]
Output: [[2, 4, 6, 7.2, 8.9]]
Method #1 : Iterating through each sublist.
Python3
list = [[ 0 , 1.2 , 3.4 , 18.1 , 10.1 ],
[ 10.3 , 12.4 , 15 , 17 , 16 , 11 ],
[ 1000 , 100 , 10 , 3.2 , 11 , 13 , 17.1 ], ]
left, right = 10 , 17
b = 0
for t in list :
a = 0
for k in t:
if k<left or k>right:
a = 1
if a = = 1 :
list .pop(b)
b = b + 1
print ( list )
|
Output:
[[10.3, 12.4, 15, 17, 16, 11]]
Time Complexity: O(n*n)
Auxiliary Space: O(1)
Method #2: Using list comprehension
Python3
list = [[ 11 , 12 , 15 , 17 , 3 ],
[ 3 , 1 , 4 , 5.2 , 9 , 19 ],
[ 2 , 4 , 6 , 7.2 , 8.9 ]]
left = 1
right = 9
Output = [i for i in list if ( min (i)> = left and max (i)< = right)]
print (Output)
|
Output:
[[2, 4, 6, 7.2, 8.9]]
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant space needed
Method #3: One additional approach that can be used to remove all sublists outside a given range is to use a filter function along with a custom function that checks if any elements in the sublist fall outside the given range.
Here is an example of how to use a filter function and a custom function to remove all sublists outside a given range:
Python3
lst = [[ 0 , 1.2 , 3.4 , 18.1 , 10.1 ],
[ 10.3 , 12.4 , 15 , 17 , 16 , 11 ],
[ 100 , 10 , 9.2 , 11 , 13 , 17.1 ]]
left, right = 10 , 17
def check_range(lst, left, right):
for i in lst:
if i < left or i > right:
return False
return True
filtered_lst = list ( filter ( lambda x: check_range(x, left, right), lst))
print (filtered_lst)
|
Output
[[10.3, 12.4, 15, 17, 16, 11]]
The filter function has a time complexity of O(n), where n is the number of elements in the input list, because it iterates over all the elements in the list. The custom function has a time complexity of O(m), where m is the number of elements in the sublist, because it iterates over all the elements in the sublist. The overall time complexity of this approach is O(nm), because both the filter function and the custom function have a linear time complexity. The space complexity of this approach is also O(nm), because the output is a new list that is the same size as the input list.
Last Updated :
17 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...