Skip to content

Commit 02aa42f

Browse files
authored
Merge pull request animator#1003 from VaishnaviMankala19/new_branch
Added Filter and Reduce Functions
2 parents 9bb081e + 2439ffe commit 02aa42f

File tree

3 files changed

+160
-0
lines changed

3 files changed

+160
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Filter Function
2+
3+
## Definition
4+
The filter function is a built-in Python function used for constructing an iterator from elements of an iterable for which a function returns true.
5+
6+
**Syntax**:
7+
```python
8+
filter(function, iterable)
9+
```
10+
**Parameters**:<br>
11+
*function*: A function that tests if each element of an iterable returns True or False.<br>
12+
*iterable*: An iterable like sets, lists, tuples, etc., whose elements are to be filtered.<br>
13+
*Returns* : An iterator that is already filtered.
14+
15+
## Basic Usage
16+
**Example 1: Filtering a List of Numbers**:
17+
```python
18+
# Define a function that returns True for even numbers
19+
def is_even(n):
20+
return n % 2 == 0
21+
22+
numbers = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
23+
even_numbers = filter(is_even, numbers)
24+
25+
# Convert the filter object to a list
26+
print(list(even_numbers)) # Output: [2, 4, 6, 8, 10]
27+
```
28+
29+
**Example 2: Filtering with a Lambda Function**:
30+
```python
31+
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
32+
odd_numbers = filter(lambda x: x % 2 != 0, numbers)
33+
34+
print(list(odd_numbers)) # Output: [1, 3, 5, 7, 9]
35+
```
36+
37+
**Example 3: Filtering Strings**:
38+
```python
39+
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape" , "python"]
40+
long_words = filter(lambda word: len(word) > 5, words)
41+
42+
print(list(long_words)) # Output: ['banana', 'cherry', 'elderberry', 'python']
43+
```
44+
45+
## Advanced Usage
46+
**Example 4: Filtering Objects with Attributes**:
47+
```python
48+
class Person:
49+
def __init__(self, name, age):
50+
self.name = name
51+
self.age = age
52+
53+
people = [
54+
Person("Alice", 30),
55+
Person("Bob", 15),
56+
Person("Charlie", 25),
57+
Person("David", 35)
58+
]
59+
60+
adults = filter(lambda person: person.age >= 18, people)
61+
adult_names = map(lambda person: person.name, adults)
62+
63+
print(list(adult_names)) # Output: ['Alice', 'Charlie', 'David']
64+
```
65+
66+
**Example 5: Using None as the Function**:
67+
```python
68+
numbers = [0, 1, 2, 3, 0, 4, 0, 5]
69+
non_zero_numbers = filter(None, numbers)
70+
71+
print(list(non_zero_numbers)) # Output: [1, 2, 3, 4, 5]
72+
```
73+
**NOTE**: When None is passed as the function, filter removes all items that are false.
74+
75+
## Time Complexity:
76+
- The time complexity of filter() depends on two factors:
77+
1. The time complexity of the filtering function (the one you provide as an argument).
78+
2. The size of the iterable being filtered.
79+
- If the filtering function has a constant time complexity (e.g., O(1)), the overall time complexity of filter() is linear (O(n)), where ‘n’ is the number of elements in the iterable.
80+
81+
## Space Complexity:
82+
- The space complexity of filter() is also influenced by the filtering function and the size of the iterable.
83+
- Since filter() returns an iterator, it doesn’t create a new list in memory. Instead, it generates filtered elements on-the-fly as you iterate over it. Therefore, the space complexity is O(1).
84+
85+
## Conclusion:
86+
Python’s filter() allows you to perform filtering operations on iterables. This kind of operation consists of applying a Boolean function to the items in an iterable and keeping only those values for which the function returns a true result. In general, you can use filter() to process existing iterables and produce new iterables containing the values that you currently need.Both versions of Python support filter(), but Python 3’s approach is more memory-efficient due to the use of iterators.

contrib/advanced-python/index.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,7 @@
1212
- [Protocols](protocols.md)
1313
- [Exception Handling in Python](exception-handling.md)
1414
- [Generators](generators.md)
15+
- [Filter](filter-function.md)
16+
- [Reduce](reduce-function.md)
1517
- [List Comprehension](list-comprehension.md)
1618
- [Eval Function](eval_function.md)
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Reduce Function
2+
3+
## Definition:
4+
The reduce() function is part of the functools module and is used to apply a binary function (a function that takes two arguments) cumulatively to the items of an iterable (e.g., a list, tuple, or string). It reduces the iterable to a single value by successively combining elements.
5+
6+
**Syntax**:
7+
```python
8+
from functools import reduce
9+
reduce(function, iterable, initial=None)
10+
```
11+
**Parameters**:<br>
12+
*function* : The binary function to apply. It takes two arguments and returns a single value.<br>
13+
*iterable* : The sequence of elements to process.<br>
14+
*initial (optional)*: An initial value. If provided, the function is applied to the initial value and the first element of the iterable. Otherwise, the first two elements are used as the initial values.
15+
16+
## Working:
17+
- Intially , first two elements of iterable are picked and the result is obtained.
18+
- Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.
19+
- This process continues till no more elements are left in the container.
20+
- The final returned result is returned and printed on console.
21+
22+
## Examples:
23+
24+
**Example 1:**
25+
```python
26+
numbers = [1, 2, 3, 4, 10]
27+
total = reduce(lambda x, y: x + y, numbers)
28+
print(total) # Output: 20
29+
```
30+
**Example 2:**
31+
```python
32+
numbers = [11, 7, 8, 20, 1]
33+
max_value = reduce(lambda x, y: x if x > y else y, numbers)
34+
print(max_value) # Output: 20
35+
```
36+
**Example 3:**
37+
```python
38+
# Importing reduce function from functools
39+
from functools import reduce
40+
41+
# Creating a list
42+
my_list = [10, 20, 30, 40, 50]
43+
44+
# Calculating the product of the numbers in my_list
45+
# using reduce and lambda functions together
46+
product = reduce(lambda x, y: x * y, my_list)
47+
48+
# Printing output
49+
print(f"Product = {product}") # Output : Product = 12000000
50+
```
51+
52+
## Difference Between reduce() and accumulate():
53+
- **Behavior:**
54+
- reduce() stores intermediate results and only returns the final summation value.
55+
- accumulate() returns an iterator containing all intermediate results. The last value in the iterator is the summation value of the list.
56+
57+
- **Use Cases:**
58+
- Use reduce() when you need a single result (e.g., total sum, product) from the iterable.
59+
- Use accumulate() when you want to access intermediate results during the reduction process.
60+
61+
- **Initial Value:**
62+
- reduce() allows an optional initial value.
63+
- accumulate() also accepts an optional initial value since Python 3.8.
64+
65+
- **Order of Arguments:**
66+
- reduce() takes the function first, followed by the iterable.
67+
- accumulate() takes the iterable first, followed by the function.
68+
69+
## Conclusion:
70+
Python's Reduce function enables us to apply reduction operations to iterables using lambda and callable functions. A
71+
function called reduce() reduces the elements of an iterable to a single cumulative value. The reduce function in
72+
Python solves various straightforward issues, including adding and multiplying iterables of numbers.

0 commit comments

Comments
 (0)