filter() in python
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
filter(function, sequence) Parameters: function: function that tests if each element of a sequence true or not. sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators. Returns: returns an iterator that is already filtered.
The filtered letters are: e e
Application: It is normally used with Lambda functions to separate list, tuple, or sets.
[1, 3, 5, 13] [0, 2, 8]
Please refer Python Lambda functions for more details.
python filter() functions:
In this program, the is_multiple_of_3() function checks if a number is a multiple of 3. The filter() function is used to apply this function to each element of the numbers list, and a for statement is used within the lambda function to iterate over each element of the list before applying the condition. This way, we can perform additional operations on each element before applying the condition.
[3, 6, 9]
Time complexity analysis:
1.The filter function is used to filter the list of numbers, and it applies the lambda function to each element of the list. The time complexity of the filter function is O(n), where n is the number of elements in the list.
2.The time complexity of the lambda function is constant, O(1), since it only performs a single arithmetic operation. Therefore, the overall time complexity of the program is O(n).
Auxiliary Space analysis:
The program uses a list to store the filtered numbers, so the space complexity is proportional to the number of filtered numbers. In the worst case, if all numbers are multiples of 3, the filtered list will have n/3 elements. Therefore, the space complexity is O(n/3), which simplifies to O(n) in big O notation.
Please Login to comment...