-
-
Notifications
You must be signed in to change notification settings - Fork 155
added reduce,map,filter #1863
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
added reduce,map,filter #1863
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
30f18f9
added reduce,map,filter
VaishnaviMankala19 e318116
Update filter-function.md
ajay-dhangar b1571f8
Updated map-function.md
VaishnaviMankala19 a20f155
Updated reduce-function.md
VaishnaviMankala19 7d68499
Updated reduce-function.md
VaishnaviMankala19 d012537
Merge branch 'CodeHarborHub:main' into py
VaishnaviMankala19 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
# Filter Function | ||
|
||
## Definition | ||
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. | ||
|
||
**Syntax**: | ||
```python | ||
filter(function, iterable) | ||
``` | ||
**Parameters**:<br> | ||
*function*: A function that tests if each element of an iterable returns True or False.<br> | ||
*iterable*: An iterable like sets, lists, tuples, etc., whose elements are to be filtered.<br> | ||
*Returns* : An iterator that is already filtered. | ||
|
||
## Basic Usage | ||
**Example 1: Filtering a List of Numbers**: | ||
```python | ||
# Define a function that returns True for even numbers | ||
def is_even(n): | ||
return n % 2 == 0 | ||
|
||
numbers = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | ||
even_numbers = filter(is_even, numbers) | ||
|
||
# Convert the filter object to a list | ||
print(list(even_numbers)) # Output: [2, 4, 6, 8, 10] | ||
``` | ||
|
||
**Example 2: Filtering with a Lambda Function**: | ||
```python | ||
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | ||
odd_numbers = filter(lambda x: x % 2 != 0, numbers) | ||
|
||
print(list(odd_numbers)) # Output: [1, 3, 5, 7, 9] | ||
``` | ||
|
||
**Example 3: Filtering Strings**: | ||
```python | ||
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape" , "python"] | ||
long_words = filter(lambda word: len(word) > 5, words) | ||
|
||
print(list(long_words)) # Output: ['banana', 'cherry', 'elderberry', 'python'] | ||
``` | ||
|
||
## Advanced Usage | ||
**Example 4: Filtering Objects with Attributes**: | ||
```python | ||
class Person: | ||
def __init__(self, name, age): | ||
self.name = name | ||
self.age = age | ||
|
||
people = [ | ||
Person("Alice", 30), | ||
Person("Bob", 15), | ||
Person("Charlie", 25), | ||
Person("David", 35) | ||
] | ||
|
||
adults = filter(lambda person: person.age >= 18, people) | ||
adult_names = map(lambda person: person.name, adults) | ||
|
||
print(list(adult_names)) # Output: ['Alice', 'Charlie', 'David'] | ||
``` | ||
|
||
**Example 5: Using None as the Function**: | ||
```python | ||
numbers = [0, 1, 2, 3, 0, 4, 0, 5] | ||
non_zero_numbers = filter(None, numbers) | ||
|
||
print(list(non_zero_numbers)) # Output: [1, 2, 3, 4, 5] | ||
``` | ||
**NOTE**: When None is passed as the function, filter removes all items that are false. | ||
|
||
## Time Complexity: | ||
- The time complexity of filter() depends on two factors: | ||
1. The time complexity of the filtering function (the one you provide as an argument). | ||
2. The size of the iterable being filtered. | ||
- 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. | ||
|
||
## Space Complexity: | ||
- The space complexity of filter() is also influenced by the filtering function and the size of the iterable. | ||
- 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). | ||
|
||
## Conclusion: | ||
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# Filter Function | ||
|
||
The `map()` function in Python is a built-in function used for applying a given function to each | ||
item of an iterable (like a list, tuple, or dictionary) and returning a new iterable with the | ||
results. It's a powerful tool for transforming data without the need for explicit loops. Let's break | ||
down its syntax, explore examples, and discuss various use cases. | ||
|
||
### Syntax: | ||
|
||
```python | ||
map(function, iterable1, iterable2, ...) | ||
``` | ||
|
||
- `function`: The function to apply to each item in the iterables. | ||
- `iterable1`, `iterable2`, ...: One or more iterable objects whose items will be passed as | ||
arguments to `function`. | ||
|
||
### Examples: | ||
|
||
#### Example 1: Doubling the values in a list | ||
|
||
```python | ||
# Define the function | ||
def double(x): | ||
return x * 2 | ||
|
||
# Apply the function to each item in the list using map | ||
original_list = [1, 2, 3, 4, 5] | ||
doubled_list = list(map(double, original_list)) | ||
print(doubled_list) # Output: [2, 4, 6, 8, 10] | ||
``` | ||
|
||
#### Example 2: Converting temperatures from Celsius to Fahrenheit | ||
|
||
```python | ||
# Define the function | ||
def celsius_to_fahrenheit(celsius): | ||
return (celsius * 9/5) + 32 | ||
|
||
# Apply the function to each Celsius temperature using map | ||
celsius_temperatures = [0, 10, 20, 30, 40] | ||
fahrenheit_temperatures = list(map(celsius_to_fahrenheit, celsius_temperatures)) | ||
print(fahrenheit_temperatures) # Output: [32.0, 50.0, 68.0, 86.0, 104.0] | ||
``` | ||
|
||
### Use Cases: | ||
|
||
1. **Data Transformation**: When you need to apply a function to each item of a collection and | ||
obtain the transformed values, `map()` is very handy. | ||
|
||
2. **Parallel Processing**: In some cases, `map()` can be utilized in parallel processing scenarios, | ||
especially when combined with `multiprocessing` or `concurrent.futures`. | ||
|
||
3. **Cleaning and Formatting Data**: It's often used in data processing pipelines for tasks like | ||
converting data types, normalizing values, or applying formatting functions. | ||
|
||
4. **Functional Programming**: In functional programming paradigms, `map()` is frequently used along | ||
with other functional constructs like `filter()` and `reduce()` for concise and expressive code. | ||
|
||
5. **Generating Multiple Outputs**: You can use `map()` to generate multiple outputs simultaneously | ||
by passing multiple iterables. The function will be applied to corresponding items in the iterables. | ||
|
||
6. **Lazy Evaluation**: In Python 3, `map()` returns an iterator rather than a list. This means it's | ||
memory efficient and can handle large datasets without loading everything into memory at once. | ||
|
||
Remember, while `map()` is powerful, it's essential to balance its use with readability and clarity. | ||
Sometimes, a simple loop might be more understandable than a `map()` call. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
# Reduce Function | ||
ajay-dhangar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
## Definition: | ||
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. | ||
|
||
**Syntax**: | ||
```python | ||
from functools import reduce | ||
reduce(function, iterable, initial=None) | ||
``` | ||
**Parameters**:<br> | ||
ajay-dhangar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*function* : The binary function to apply. It takes two arguments and returns a single value.<br> | ||
ajay-dhangar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*iterable* : The sequence of elements to process.<br> | ||
ajay-dhangar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*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 | ||
ajay-dhangar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
values. | ||
|
||
## Working: | ||
- Intially , first two elements of iterable are picked and the result is obtained. | ||
- 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. | ||
- This process continues till no more elements are left in the container. | ||
- The final returned result is returned and printed on console. | ||
|
||
## Examples: | ||
|
||
**Example 1:** | ||
```python | ||
numbers = [1, 2, 3, 4, 10] | ||
total = reduce(lambda x, y: x + y, numbers) | ||
print(total) # Output: 20 | ||
``` | ||
**Example 2:** | ||
```python | ||
numbers = [11, 7, 8, 20, 1] | ||
max_value = reduce(lambda x, y: x if x > y else y, numbers) | ||
print(max_value) # Output: 20 | ||
``` | ||
**Example 3:** | ||
```python | ||
# Importing reduce function from functools | ||
from functools import reduce | ||
|
||
# Creating a list | ||
my_list = [10, 20, 30, 40, 50] | ||
|
||
# Calculating the product of the numbers in my_list | ||
# using reduce and lambda functions together | ||
product = reduce(lambda x, y: x * y, my_list) | ||
|
||
# Printing output | ||
print(f"Product = {product}") # Output : Product = 12000000 | ||
``` | ||
|
||
## Difference Between reduce() and accumulate(): | ||
- **Behavior:** | ||
- reduce() stores intermediate results and only returns the final summation value. | ||
- accumulate() returns an iterator containing all intermediate results. The last value in the | ||
iterator is the summation value of the list. | ||
|
||
- **Use Cases:** | ||
- Use reduce() when you need a single result (e.g., total sum, product) from the iterable. | ||
- Use accumulate() when you want to access intermediate results during the reduction process. | ||
|
||
- **Initial Value:** | ||
- reduce() allows an optional initial value. | ||
- accumulate() also accepts an optional initial value since Python 3.8. | ||
|
||
- **Order of Arguments:** | ||
- reduce() takes the function first, followed by the iterable. | ||
- accumulate() takes the iterable first, followed by the function. | ||
|
||
## Conclusion: | ||
Python's Reduce function enables us to apply reduction operations to iterables using lambda and call | ||
able functions. A function called reduce() reduces the elements of an iterable to a single | ||
cumulative value. The reduce function in Python solves various straightforward issues, including | ||
adding and multiplying iterables of numbers. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.