Skip to content

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 6 commits into from
Jun 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions docs/python/Advanced Concepts/filter-function.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
---
id: filter-function
title: Filter Function in Python
sidebar_label: 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**:

- **function:** A function that tests if each element of an iterable returns True or False.
- **iterable:** An iterable like sets, lists, tuples, etc., whose elements are to be filtered.
- **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.
71 changes: 71 additions & 0 deletions docs/python/Advanced Concepts/map-function.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
id: map-function
title: Map Function in Python
sidebar_label: Map 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.
83 changes: 83 additions & 0 deletions docs/python/Advanced Concepts/reduce-function.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
id: reduce-function
title: Reduce Function in Python
sidebar_label: Reduce Function
---

## 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 />
*function* : The binary function to apply. It takes two arguments and returns a single value.<br />
*iterable* : The sequence of elements to process.<br />
*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.

## 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.
Loading