Merge branch 'animator:main' into main

pull/1105/head
Mr.Cody_Rohit 2024-06-10 01:13:16 +05:30 zatwierdzone przez GitHub
commit c51ad25a9f
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: B5690EEEBB952194
24 zmienionych plików z 1600 dodań i 0 usunięć

Wyświetl plik

@ -0,0 +1,101 @@
# Closures
In order to have complete understanding of this topic in python, one needs to be crystal clear with the concept of functions and the different types of them which are namely First Class Functions and Nested Functions.
### First Class Functions
These are the normal functions used by the programmer in routine as they can be assigned to variables, passed as arguments and returned from other functions.
### Nested Functions
These are the functions defined within other functions and involve thorough usage of **Closures**. It is also referred as **Inner Functions** by some books. There are times when it is required to prevent a function or the data it has access to from being accessed from other parts of the code, and this is where Nested Functions come into play. Basically, its usage allows the encapsulation of that particular data/function within another function. This enables it to be virtually hidden from the global scope.
## Defining Closures
In nested functions, if the outer function basically ends up returning the inner function, in this case the concept of closures comes into play.
A closure is a function object that remembers values in enclosing scopes even if they are not present in memory. There are certain neccesary condtions required to create a closure in python :
1. The inner function must be defined inside the outer function.
2. The inner function must refer to a value defined in the outer function.
3. The inner function must return a value.
## Advantages of Closures
* Closures make it possible to pass data to inner functions without first passing them to outer functions
* Closures can be used to create private variables and functions
* They also make it possible to invoke the inner function from outside of the encapsulating outer function.
* It improves code readability and maintainability
## Examples implementing Closures
### Example 1 : Basic Implementation
```python
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
times3 = make_multiplier_of(3)
times5 = make_multiplier_of(5)
print(times3(9))
print(times5(3))
```
#### Output:
```
27
15
```
The **multiplier function** is defined inside the **make_multiplier_of function**. It has access to the n variable from the outer scope, even after the make_multiplier_of function has returned. This is an example of a closure.
### Example 2 : Implementation with Decorators
```python
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(f"Wrapper executed before {original_function.__name__}")
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display():
print("Display function executed")
display()
```
#### Output:
```
Wrapper executed before display
Display function executed
```
The code in the example defines a decorator function: ***decorator_function*** that takes a function as an argument and returns a new function **wrapper_function**. The **wrapper_function** function prints a message to the console before calling the original function which appends the name of the called function as specified in the code.
The **@decorator_function** syntax is used to apply the decorator_function decorator to the display function. This means that the display function is replaced with the result of calling **decorator_function(display)**.
When the **display()** function is called, the wrapper_function function is executed instead. The wrapper_function function prints a message to the console and then calls the original display function.
### Example 3 : Implementation with for loop
```python
def create_closures():
closures = []
for i in range(5):
def closure(i=i): # Capture current value of i by default argument
return i
closures.append(closure)
return closures
my_closures = create_closures()
for closure in my_closures:
print(closure())
```
#### Output:
```
0
1
2
3
4
```
The code in the example defines a function **create_closures** that creates a list of closure functions. Each closure function returns the current value of the loop variable i.
The closure function is defined inside the **create_closures function**. It has access to the i variable from the **outer scope**, even after the create_closures function has returned. This is an example of a closure.
The **i**=*i* argument in the closure function is used to capture the current value of *i* by default argument. This is necessary because the ****i** variable in the outer scope is a loop variable, and its value changes in each iteration of the loop. By capturing the current value of *i* in the default argument, we ensure that each closure function returns the correct value of **i**. This is responsible for the generation of output 0,1,2,3,4.
For more examples related to closures, [click here](https://dev.to/bshadmehr/understanding-closures-in-python-a-comprehensive-tutorial-11ld).
## Summary
Closures in Python provide a powerful mechanism for encapsulating state and behavior, enabling more flexible and modular code. Understanding and effectively using closures enables the creation of function factories, allows functions to have state, and facilitates functional programming techniques

Wyświetl plik

@ -0,0 +1,75 @@
# Understanding the `eval` Function in Python
## Introduction
The `eval` function in Python allows you to execute a string-based Python expression dynamically. This can be useful in various scenarios where you need to evaluate expressions that are not known until runtime.
## Syntax
```python
eval(expression, globals=None, locals=None)
```
### Parameters:
* expression: String is parsed and evaluated as a Python expression
* globals [optional]: Dictionary to specify the available global methods and variables.
* locals [optional]: Another dictionary to specify the available local methods and variables.
## Examples
Example 1:
```python
result = eval('2 + 3 * 4')
print(result) # Output: 14
```
Example 2:
```python
x = 10
expression = 'x * 2'
result = eval(expression, {'x': x})
print(result) # Output: 20
```
Example 3:
```python
x = 10
def multiply(a, b):
return a * b
expression = 'multiply(x, 5) + 2'
result = eval(expression)
print("Result:",result) # Output: Result:52
```
Example 4:
```python
expression = input("Enter a Python expression: ")
result = eval(expression)
print("Result:", result)
#input= "3+2"
#Output: Result:5
```
Example 5:
```python
import numpy as np
a=np.random.randint(1,9)
b=np.random.randint(1,9)
operations=["*","-","+"]
op=np.random.choice(operations)
expression=str(a)+op+str(b)
correct_answer=eval(expression)
given_answer=int(input(str(a)+" "+op+" "+str(b)+" = "))
if given_answer==correct_answer:
print("Correct")
else:
print("Incorrect")
print("correct answer is :" ,correct_answer)
#2 * 1 = 8
#Incorrect
#correct answer is : 2
#or
#3 * 2 = 6
#Correct
```
## Conclusion
The eval function is a powerful tool in Python that allows for dynamic evaluation of expressions.

Wyświetl plik

@ -0,0 +1,86 @@
# 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 doesnt 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:
Pythons 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 3s approach is more memory-efficient due to the use of iterators.

Wyświetl plik

@ -2,6 +2,8 @@
- [OOPs](oops.md)
- [Decorators/\*args/**kwargs](decorator-kwargs-args.md)
- ['itertools' module](itertools.md)
- [Type Hinting](type-hinting.md)
- [Lambda Function](lambda-function.md)
- [Working with Dates & Times in Python](dates_and_times.md)
- [Regular Expressions in Python](regular_expressions.md)
@ -10,3 +12,9 @@
- [Protocols](protocols.md)
- [Exception Handling in Python](exception-handling.md)
- [Generators](generators.md)
- [Match Case Statement](match-case.md)
- [Closures](closures.md)
- [Filter](filter-function.md)
- [Reduce](reduce-function.md)
- [List Comprehension](list-comprehension.md)
- [Eval Function](eval_function.md)

Wyświetl plik

@ -0,0 +1,144 @@
# The 'itertools' Module in Python
The itertools module in Python provides a collection of fast, memory-efficient tools that are useful for creating and working with iterators. These functions
allow you to iterate over data in various ways, often combining, filtering, or extending iterators to generate complex sequences efficiently.
## Benefits of itertools
1. Efficiency: Functions in itertools are designed to be memory-efficient, often generating elements on the fly and avoiding the need to store large intermediate results.
2. Conciseness: Using itertools can lead to more readable and concise code, reducing the need for complex loops and temporary variables.
3. Composability: Functions from itertools can be easily combined, allowing you to build complex iterator pipelines from simple building blocks.
## Useful Functions in itertools <br>
Here are some of the most useful functions in the itertools module, along with examples of how to use them:
1. 'count': Generates an infinite sequence of numbers, starting from a specified value.
```bash
import itertools
counter = itertools.count(start=10, step=2)
for _ in range(5):
print(next(counter))
# Output: 10, 12, 14, 16, 18
```
2. 'cycle': Cycles through an iterable indefinitely.
```bash
import itertools
cycler = itertools.cycle(['A', 'B', 'C'])
for _ in range(6):
print(next(cycler))
# Output: A, B, C, A, B, C
```
3.'repeat': Repeats an object a specified number of times or indefinitely.
```bash
import itertools
repeater = itertools.repeat('Hello', 3)
for item in repeater:
print(item)
# Output: Hello, Hello, Hello
```
4. 'chain': Combines multiple iterables into a single iterable.
```bash
import itertools
combined = itertools.chain([1, 2, 3], ['a', 'b', 'c'])
for item in combined:
print(item)
# Output: 1, 2, 3, a, b, c
```
5. 'islice': Slices an iterator, similar to slicing a list.
```bash
import itertools
sliced = itertools.islice(range(10), 2, 8, 2)
for item in sliced:
print(item)
# Output: 2, 4, 6
```
6. 'compress': Filters elements in an iterable based on a corresponding selector iterable.
```bash
import itertools
data = ['A', 'B', 'C', 'D']
selectors = [1, 0, 1, 0]
result = itertools.compress(data, selectors)
for item in result:
print(item)
# Output: A, C
```
7. 'permutations': Generates all possible permutations of an iterable.
```bash
import itertools
perms = itertools.permutations('ABC', 2)
for item in perms:
print(item)
# Output: ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')
```
8. 'combinations': Generates all possible combinations of a specified length from an iterable.
```bash
import itertools
combs = itertools.combinations('ABC', 2)
for item in combs:
print(item)
# Output: ('A', 'B'), ('A', 'C'), ('B', 'C')
```
9. 'product': Computes the Cartesian product of input iterables.
```bash
import itertools
prod = itertools.product('AB', '12')
for item in prod:
print(item)
# Output: ('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')
```
10. 'groupby': Groups elements of an iterable by a specified key function.
```bash
import itertools
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 30}]
sorted_data = sorted(data, key=lambda x: x['age'])
grouped = itertools.groupby(sorted_data, key=lambda x: x['age'])
for key, group in grouped:
print(key, list(group))
# Output:
# 25 [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 25}]
# 30 [{'name': 'Charlie', 'age': 30}]
```
11. 'accumulate': Makes an iterator that returns accumulated sums, or accumulated results of other binary functions specified via the optional func argument.
```bash
import itertools
import operator
data = [1, 2, 3, 4, 5]
acc = itertools.accumulate(data, operator.mul)
for item in acc:
print(item)
# Output: 1, 2, 6, 24, 120
```
## Conclusion
The itertools module is a powerful toolkit for working with iterators in Python. Its functions enable efficient and concise handling of iterable data, allowing you to create complex data processing pipelines with minimal memory overhead.
By leveraging itertools, you can improve the readability and performance of your code, making it a valuable addition to your Python programming arsenal.

Wyświetl plik

@ -0,0 +1,73 @@
# List Comprehension
Creating lists concisely and expressively is what list comprehension in Python does. You can generate lists from already existing iterables like lists, tuples or strings with a short form.
This boosts the readability of code and reduces necessity of using explicit looping constructs.
## Syntax :
### Basic syntax
```python
new_list = [expression for item in iterable]
```
- **new_list**: This is the name given to the list that will be created using the list comprehension.
- **expression**: This is the expression that defines how each element of the new list will be generated or transformed.
- **item**: This variable represents each individual element from the iterable. It takes on the value of each element in the iterable during each iteration.
- **iterable**: This is the sequence-like object over which the iteration will take place. It provides the elements that will be processed by the expression.
This list comprehension syntax `[expression for item in iterable]` allows you to generate a new list by applying a specific expression to each element in an iterable.
### Syntax including condition
```python
new_list = [expression for item in iterable if condition]
```
- **new_list**: This is the name given to the list that will be created using the list comprehension.
- **expression**: This is the expression that defines how each element of the new list will be generated or transformed.
- **item**: This variable represents each individual element from the iterable. It takes on the value of each element in the iterable during each iteration.
- **iterable**: This is the sequence-like object over which the iteration will take place. It provides the elements that will be processed by the expression.
- **if condition**: This is an optional part of the syntax. It allows for conditional filtering of elements from the iterable. Only items that satisfy the condition
will be included in the new list.
## Examples:
1. Generating a list of squares of numbers from 1 to 5:
```python
squares = [x ** 2 for x in range(1, 6)]
print(squares)
```
- **Output** :
```python
[1, 4, 9, 16, 25]
```
2. Filtering even numbers from a list:
```python
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = [x for x in nums if x % 2 == 0]
print(even)
```
- **Output** :
```python
[2, 4, 6, 8, 10]
```
3. Flattening a list of lists:
```python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for sublist in matrix for x in sublist]
print(flat)
```
- **Output** :
```python
[1, 2, 3, 4, 5, 6, 7, 8, 9]
```
List comprehension is a powerful feature in Python for creating lists based on existing iterables with a concise syntax.
By mastering list comprehension, developers can write cleaner, more expressive code and leverage Python's functional programming capabilities effectively.

Wyświetl plik

@ -0,0 +1,251 @@
# Match Case Statements
## Introduction
Match and case statements are introduced in Python 3.10 for structural pattern matching of patterns with associated actions. It offers more readible and
cleaniness to the code as opposed to the traditional `if-else` statements. They also have destructuring, pattern matching and checks for specific properties in
addition to the traditional `switch-case` statements in other languages, which makes them more versatile.
## Syntax
```
match <statement>:
case <pattern_1>:
<do_task_1>
case <pattern_2>:
<do_task_2>
case _:
<do_task_wildcard>
```
A match statement takes a statement which compares it to the various cases and their patterns. If any of the pattern is matched successively, the task is performed accordingly. If an exact match is not confirmed, the last case, a wildcard `_`, if provided, will be used as the matching case.
## Pattern Matching
As discussed earlier, match case statements use pattern matching where the patterns consist of sequences, mappings, primitive data types as well as class instances. The structural pattern matching uses declarative approach and it nexplicitly states the conditions for the patterns to match with the data.
### Patterns with a Literal
#### Generic Case
`sample text` is passed as a literal in the `match` block. There are two cases and a wildcard case mentioned.
```python
match 'sample text':
case 'sample text':
print('sample text')
case 'sample':
print('sample')
case _:
print('None found')
```
The `sample text` case is satisfied as it matches with the literal `sample text` described in the `match` block.
O/P:
```
sample text
```
#### Using OR
Taking another example, `|` can be used as OR to include multiple patterns in a single case statement where the multiple patterns all lead to a similar task.
The below code snippets can be used interchangebly and generate the similar output. The latter is more consive and readible.
```python
match 'e':
case 'a':
print('vowel')
case 'e':
print('vowel')
case 'i':
print('vowel')
case 'o':
print('vowel')
case 'u':
print('vowel')
case _:
print('consonant')
```
```python
match 'e':
case 'a' | 'e' | 'i' | 'o' | 'u':
print('vowel')
case _:
print('consonant')
```
O/P:
```
vowel
```
#### Without wildcard
When in a `match` block, there is no wildcard case present there are be two cases of match being present or not. If the match doesn't exist, the behaviour is a no-op.
```python
match 'c':
case 'a' | 'e' | 'i' | 'o' | 'u':
print('vowel')
```
The output will be blank as a no-op occurs.
### Patterns with a Literal and a Variable
Pattern matching can be done by unpacking the assignments and also bind variables with it.
```python
def get_names(names: str) -> None:
match names:
case ('Bob', y):
print(f'Hello {y}')
case (x, 'John'):
print(f'Hello {x}')
case (x, y):
print(f'Hello {x} and {y}')
case _:
print('Invalid')
```
Here, the `names` is a tuple that contains two names. The `match` block unpacks the tuple and binds `x` and `y` based on the patterns. A wildcard case prints `Invalid` if the condition is not satisfied.
O/P:
In this example, the above code snippet with the parameter `names` as below and the respective output.
```
>>> get_names(('Bob', 'Max'))
Hello Max
>>> get_names(('Rob', 'John'))
Hello Rob
>>> get_names(('Rob', 'Max'))
Hello Rob and Max
>>> get_names(('Rob', 'Max', 'Bob'))
Invalid
```
### Patterns with Classes
Class structures can be used in `match` block for pattern matching. The class members can also be binded with a variable to perform certain operations. For the class structure:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
```
The match case example illustrates the generic working as well as the binding of variables with the class members.
```python
def get_class(cls: Person) -> None:
match cls:
case Person(name='Bob', age=18):
print('Hello Bob with age 18')
case Person(name='Max', age=y):
print(f'Age is {y}')
case Person(name=x, age=18):
print(f'Name is {x}')
case Person(name=x, age=y):
print(f'Name and age is {x} and {y}')
case _:
print('Invalid')
```
O/P:
```
>>> get_class(Person('Bob', 18))
Hello Bob with age 18
>>> get_class(Person('Max', 21))
Age is 21
>>> get_class(Person('Rob', 18))
Name is Rob
>>> get_class(Person('Rob', 21))
Name and age is Rob and 21
```
Now, if a new class is introduced in the above code snippet like below.
```python
class Pet:
def __init__(self, name, animal):
self.name = name
self.animal = animal
```
The patterns will not match the cases and will trigger the wildcard case for the original code snippet above with `get_class` function.
```
>>> get_class(Pet('Tommy', 'Dog'))
Invalid
```
### Nested Patterns
The patterns can be nested via various means. It can include the mix of the patterns mentioned earlier or can be symmetrical across. A basic of the nested pattern of a list with Patterns with a Literal and Variable is taken. Classes and Iterables can laso be included.
```python
def get_points(points: list) -> None:
match points:
case []:
print('Empty')
case [x]:
print(f'One point {x}')
case [x, y]:
print(f'Two points {x} and {y}')
case _:
print('More than two points')
```
O/P:
```
>>> get_points([])
Empty
>>> get_points([1])
One point 1
>>> get_points([1, 2])
Two points 1 and 2
>>> get_points([1, 2, 3])
More than two points
```
### Complex Patterns
Complex patterns are also supported in the pattern matching sequence. The complex does not mean complex numbers but rather the structure which makes the readibility to seem complex.
#### Wildcard
The wildcard used till now are in the form of `case _` where the wildcard case is used if no match is found. Furthermore, the wildcard `_` can also be used as a placeholder in complex patterns.
```python
def wildcard(value: tuple) -> None:
match value:
case ('Bob', age, 'Mechanic'):
print(f'Bob is mechanic of age {age}')
case ('Bob', age, _):
print(f'Bob is not a mechanic of age {age}')
```
O/P:
The value in the above snippet is a tuple with `(Name, Age, Job)`. If the job is Mechanic and the name is Bob, the first case is triggered. But if the job is different and not a mechanic, then the other case is triggered with the wildcard.
```
>>> wildcard(('Bob', 18, 'Mechanic'))
Bob is mechanic of age 18
>>> wildcard(('Bob', 21, 'Engineer'))
Bob is not a mechanic of age 21
```
#### Guard
A `guard` is when an `if` is added to a pattern. The evaluation depends on the truth value of the guard.
`nums` is the tuple which contains two integers. A guard is the first case where it checks whether the first number is greater or equal to the second number in the tuple. If it is false, then it moves to the second case, where it concludes that the first number is smaller than the second number.
```python
def guard(nums: tuple) -> None:
match nums:
case (x, y) if x >= y:
print(f'{x} is greater or equal than {y}')
case (x, y):
print(f'{x} is smaller than {y}')
case _:
print('Invalid')
```
O/P:
```
>>> guard((1, 2))
1 is smaller than 2
>>> guard((2, 1))
2 is greater or equal than 1
>>> guard((1, 1))
1 is greater or equal than 1
```
## Summary
The match case statements provide an elegant and readible format to perform operations on pattern matching as compared to `if-else` statements. They are also more versatile as they provide additional functionalities on the pattern matching operations like unpacking, class matching, iterables and iterators. It can also use positional arguments for checking the patterns. They provide a powerful and concise way to handle multiple conditions and perform pattern matching
## Further Reading
This article provides a brief introduction to the match case statements and the overview on the pattern matching operations. To know more, the below articles can be used for in-depth understanding of the topic.
- [PEP 634 – Structural Pattern Matching: Specification](https://peps.python.org/pep-0634/)
- [PEP 636 – Structural Pattern Matching: Tutorial](https://peps.python.org/pep-0636/)

Wyświetl plik

@ -0,0 +1,72 @@
# 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 callable 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.

Wyświetl plik

@ -0,0 +1,106 @@
# Introduction to Type Hinting in Python
Type hinting is a feature in Python that allows you to specify the expected data types of variables, function arguments, and return values. It was introduced
in Python 3.5 via PEP 484 and has since become a standard practice to improve code readability and facilitate static analysis tools.
**Benefits of Type Hinting**
1. Improved Readability: Type hints make it clear what type of data is expected, making the code easier to understand for others and your future self.
2. Error Detection: Static analysis tools like MyPy can use type hints to detect type errors before runtime, reducing bugs and improving code quality.
3.Better Tooling Support: Modern IDEs and editors can leverage type hints to provide better autocompletion, refactoring, and error checking features.
4. Documentation: Type hints serve as a form of documentation, indicating the intended usage of functions and classes.
**Syntax of Type Hinting** <br>
Type hints can be added to variables, function arguments, and return values using annotations.
1. Variable Annotations:
```bash
age: int = 25
name: str = "Alice"
is_student: bool = True
```
2. Function Annotations:
```bash
def greet(name: str) -> str:
return f"Hello, {name}!"
```
3. Multiple Arguments and Return Types:
```bash
def add(a: int, b: int) -> int:
return a + b
```
4. Optional Types: Use the Optional type from the typing module for values that could be None.
```bash
from typing import Optional
def get_user_name(user_id: int) -> Optional[str]:
# Function logic here
return None # Example return value
```
5. Union Types: Use the Union type when a variable can be of multiple types.
```bash
from typing import Union
def get_value(key: str) -> Union[int, str]:
# Function logic here
return "value" # Example return value
```
6. List and Dictionary Types: Use the List and Dict types from the typing module for collections.
```bash
from typing import List, Dict
def process_data(data: List[int]) -> Dict[str, int]:
# Function logic here
return {"sum": sum(data)} # Example return value
```
7. Type Aliases: Create type aliases for complex types to make the code more readable.
```bash
from typing import List, Tuple
Coordinates = List[Tuple[int, int]]
def draw_shape(points: Coordinates) -> None:
# Function logic here
pass
```
**Example of Type Hinting in a Class** <br>
Here is a more comprehensive example using type hints in a class:
```bash
from typing import List
class Student:
def __init__(self, name: str, age: int, grades: List[int]) -> None:
self.name = name
self.age = age
self.grades = grades
def average_grade(self) -> float:
return sum(self.grades) / len(self.grades)
def add_grade(self, grade: int) -> None:
self.grades.append(grade)
# Example usage
student = Student("Alice", 20, [90, 85, 88])
print(student.average_grade()) # Output: 87.66666666666667
student.add_grade(92)
print(student.average_grade()) # Output: 88.75
```
### Conclusion
Type hinting in Python enhances code readability, facilitates error detection through static analysis, and improves tooling support. By adopting
type hinting, you can write clearer and more maintainable code, reducing the likelihood of bugs and making your codebase easier to navigate for yourself and others.

Wyświetl plik

@ -0,0 +1,153 @@
# Hashing with Chaining
In Data Structures and Algorithms, hashing is used to map data of arbitrary size to fixed-size values. A common approach to handle collisions in hashing is **chaining**. In chaining, each slot of the hash table contains a linked list, and all elements that hash to the same slot are stored in that list.
## Points to be Remembered
- **Hash Function**: A function that converts an input (or 'key') into an index in a hash table.
- **Collision**: When two keys hash to the same index.
- **Chaining**: A method to resolve collisions by maintaining a linked list for each hash table slot.
## Real Life Examples of Hashing with Chaining
- **Phone Directory**: Contacts are stored in a hash table where the contact's name is hashed to an index. If multiple names hash to the same index, they are stored in a linked list at that index.
- **Library Catalog**: Books are indexed by their titles. If multiple books have titles that hash to the same index, they are stored in a linked list at that index.
## Applications of Hashing
Hashing is widely used in Computer Science:
- **Database Indexing**
- **Caches** (like CPU caches, web caches)
- **Associative Arrays** (or dictionaries in Python)
- **Sets** (unordered collections of unique elements)
Understanding these applications is essential for Software Development.
## Operations in Hash Table with Chaining
Key operations include:
- **INSERT**: Insert a new element into the hash table.
- **SEARCH**: Find the position of an element in the hash table.
- **DELETE**: Remove an element from the hash table.
## Implementing Hash Table with Chaining in Python
```python
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class HashTable:
def __init__(self, size):
self.size = size
self.table = [None] * size
def hash_function(self, key):
return key % self.size
def insert(self, key, value):
hash_index = self.hash_function(key)
new_node = Node(key, value)
if self.table[hash_index] is None:
self.table[hash_index] = new_node
else:
current = self.table[hash_index]
while current.next is not None:
current = current.next
current.next = new_node
def search(self, key):
hash_index = self.hash_function(key)
current = self.table[hash_index]
while current is not None:
if current.key == key:
return current.value
current = current.next
return None
def delete(self, key):
hash_index = self.hash_function(key)
current = self.table[hash_index]
prev = None
while current is not None:
if current.key == key:
if prev is None:
self.table[hash_index] = current.next
else:
prev.next = current.next
return True
prev = current
current = current.next
return False
def display(self):
for index, item in enumerate(self.table):
print(f"Index {index}:", end=" ")
current = item
while current is not None:
print(f"({current.key}, {current.value})", end=" -> ")
current = current.next
print("None")
# Example usage
hash_table = HashTable(10)
hash_table.insert(1, 'A')
hash_table.insert(11, 'B')
hash_table.insert(21, 'C')
print("Hash Table after Insert operations:")
hash_table.display()
print("Search operation for key 11:", hash_table.search(11))
hash_table.delete(11)
print("Hash Table after Delete operation:")
hash_table.display()
```
## Output
```markdown
Hash Table after Insert operations:
Index 0: None
Index 1: (1, 'A') -> (11, 'B') -> (21, 'C') -> None
Index 2: None
Index 3: None
Index 4: None
Index 5: None
Index 6: None
Index 7: None
Index 8: None
Index 9: None
Search operation for key 11: B
Hash Table after Delete operation:
Index 0: None
Index 1: (1, 'A') -> (21, 'C') -> None
Index 2: None
Index 3: None
Index 4: None
Index 5: None
Index 6: None
Index 7: None
Index 8: None
Index 9: None
```
## Complexity Analysis
- **Insertion**: Average case O(1), Worst case O(n) when many elements hash to the same slot.
- **Search**: Average case O(1), Worst case O(n) when many elements hash to the same slot.
- **Deletion**: Average case O(1), Worst case O(n) when many elements hash to the same slot.

Wyświetl plik

@ -0,0 +1,139 @@
# Hashing with Linear Probing
In Data Structures and Algorithms, hashing is used to map data of arbitrary size to fixed-size values. A common approach to handle collisions in hashing is **linear probing**. In linear probing, if a collision occurs (i.e., the hash value points to an already occupied slot), we linearly probe through the table to find the next available slot. This method ensures that every element can be inserted or found in the hash table.
## Points to be Remembered
- **Hash Function**: A function that converts an input (or 'key') into an index in a hash table.
- **Collision**: When two keys hash to the same index.
- **Linear Probing**: A method to resolve collisions by checking the next slot (i.e., index + 1) until an empty slot is found.
## Real Life Examples of Hashing with Linear Probing
- **Student Record System**: Each student record is stored in a table where the student's ID number is hashed to an index. If two students have the same hash index, linear probing finds the next available slot.
- **Library System**: Books are indexed by their ISBN numbers. If two books hash to the same slot, linear probing helps find another spot for the book in the catalog.
## Applications of Hashing
Hashing is widely used in Computer Science:
- **Database Indexing**
- **Caches** (like CPU caches, web caches)
- **Associative Arrays** (or dictionaries in Python)
- **Sets** (unordered collections of unique elements)
Understanding these applications is essential for Software Development.
## Operations in Hash Table with Linear Probing
Key operations include:
- **INSERT**: Insert a new element into the hash table.
- **SEARCH**: Find the position of an element in the hash table.
- **DELETE**: Remove an element from the hash table.
## Implementing Hash Table with Linear Probing in Python
```python
class HashTable:
def __init__(self, size):
self.size = size
self.table = [None] * size
def hash_function(self, key):
return key % self.size
def insert(self, key, value):
hash_index = self.hash_function(key)
if self.table[hash_index] is None:
self.table[hash_index] = (key, value)
else:
while self.table[hash_index] is not None:
hash_index = (hash_index + 1) % self.size
self.table[hash_index] = (key, value)
def search(self, key):
hash_index = self.hash_function(key)
while self.table[hash_index] is not None:
if self.table[hash_index][0] == key:
return self.table[hash_index][1]
hash_index = (hash_index + 1) % self.size
return None
def delete(self, key):
hash_index = self.hash_function(key)
while self.table[hash_index] is not None:
if self.table[hash_index][0] == key:
self.table[hash_index] = None
return True
hash_index = (hash_index + 1) % self.size
return False
def display(self):
for index, item in enumerate(self.table):
print(f"Index {index}: {item}")
# Example usage
hash_table = HashTable(10)
hash_table.insert(1, 'A')
hash_table.insert(11, 'B')
hash_table.insert(21, 'C')
print("Hash Table after Insert operations:")
hash_table.display()
print("Search operation for key 11:", hash_table.search(11))
hash_table.delete(11)
print("Hash Table after Delete operation:")
hash_table.display()
```
## Output
```markdown
Hash Table after Insert operations:
Index 0: None
Index 1: (1, 'A')
Index 2: None
Index 3: None
Index 4: None
Index 5: None
Index 6: None
Index 7: None
Index 8: None
Index 9: None
Index 10: None
Index 11: (11, 'B')
Index 12: (21, 'C')
Search operation for key 11: B
Hash Table after Delete operation:
Index 0: None
Index 1: (1, 'A')
Index 2: None
Index 3: None
Index 4: None
Index 5: None
Index 6: None
Index 7: None
Index 8: None
Index 9: None
Index 10: None
Index 11: None
Index 12: (21, 'C')
```
## Complexity Analysis
- **Insertion**: Average case O(1), Worst case O(n) when many collisions occur.
- **Search**: Average case O(1), Worst case O(n) when many collisions occur.
- **Deletion**: Average case O(1), Worst case O(n) when many collisions occur.

Wyświetl plik

@ -13,3 +13,6 @@
- [Stacks in Python](stacks.md)
- [Sliding Window Technique](sliding-window.md)
- [Trie](trie.md)
- [Two Pointer Technique](two-pointer-technique.md)
- [Hashing through Linear Probing](hashing-linear-probing.md)
- [Hashing through Chaining](hashing-chaining.md)

Wyświetl plik

@ -465,3 +465,99 @@ print("Sorted array:", arr) # Output: [1, 2, 3, 5, 8]
- **Worst Case:** `𝑂(𝑛log𝑛)`. Building the heap takes `𝑂(𝑛)` time, and each of the 𝑛 element extractions takes `𝑂(log𝑛)` time.
- **Best Case:** `𝑂(𝑛log𝑛)`. Even if the array is already sorted, heap sort will still build the heap and perform the extractions.
- **Average Case:** `𝑂(𝑛log𝑛)`. Similar to the worst-case, the overall complexity remains `𝑂(𝑛log𝑛)` because each insertion and deletion in a heap takes `𝑂(log𝑛)` time, and these operations are performed 𝑛 times.
## 7. Radix Sort
Radix Sort is a non-comparative integer sorting algorithm that sorts numbers by processing individual digits. It processes digits from the least significant digit (LSD) to the most significant digit (MSD) or vice versa. This algorithm is efficient for sorting numbers with a fixed number of digits.
**Algorithm Overview:**
- **Digit by Digit sorting:** Radix sort processes the digits of the numbers starting from either the least significant digit (LSD) or the most significant digit (MSD). Typically, LSD is used.
- **Stable Sort:** A stable sorting algorithm like Counting Sort or Bucket Sort is used as an intermediate sorting technique. Radix Sort relies on this stability to maintain the relative order of numbers with the same digit value.
- **Multiple passes:** The algorithm performs multiple passes over the numbers, one for each digit, from the least significant to the most significant.
### Radix Sort Code in Python
```python
def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1
for i in range(n):
arr[i] = output[i]
def radix_sort(arr):
max_num = max(arr)
exp = 1
while max_num // exp > 0:
counting_sort(arr, exp)
exp *= 10
# Example usage
arr = [170, 45, 75, 90]
print("Original array:", arr)
radix_sort(arr)
print("Sorted array:", arr)
```
### Complexity Analysis
- **Time Complexity:** O(d * (n + k)) for all cases. Radix Sort always processes each digit of every number in the array.
- **Space Complexity:** O(n + k). This is due to the space required for:
- The output array used in Counting Sort, which is of size n.
- The count array used in Counting Sort, which is of size k.
## 8. Counting Sort
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then do some arithmetic to calculate the position of each object in the output sequence.
**Algorithm Overview:**
- Convert the input string into a list of characters.
- Count the occurrence of each character in the list using the collections.Counter() method.
- Sort the keys of the resulting Counter object to get the unique characters in the list in sorted order.
- For each character in the sorted list of keys, create a list of repeated characters using the corresponding count from the Counter object.
- Concatenate the lists of repeated characters to form the sorted output list.
### Counting Sort Code in Python using counter method.
```python
from collections import Counter
def counting_sort(arr):
count = Counter(arr)
output = []
for c in sorted(count.keys()):
output += * count
return output
arr = "geeksforgeeks"
arr = list(arr)
arr = counting_sort(arr)
output = ''.join(arr)
print("Sorted character array is", output)
```
### Counting Sort Code in Python using sorted() and reduce():
```python
from functools import reduce
string = "geeksforgeeks"
sorted_str = reduce(lambda x, y: x+y, sorted(string))
print("Sorted string:", sorted_str)
```
### Complexity Analysis
- **Time Complexity:** O(n+k) for all cases.No matter how the elements are placed in the array, the algorithm goes through n+k times
- **Space Complexity:** O(max). Larger the range of elements, larger is the space complexity.

Wyświetl plik

@ -0,0 +1,132 @@
# Two-Pointer Technique
---
- The two-pointer technique is a popular algorithmic strategy used to solve various problems efficiently. This technique involves using two pointers (or indices) to traverse through data structures such as arrays or linked lists.
- The pointers can move in different directions, allowing for efficient processing of elements to achieve the desired results.
## Common Use Cases
1. **Finding pairs in a sorted array that sum to a target**: One pointer starts at the beginning and the other at the end.
2. **Reversing a linked list**: One pointer starts at the head, and the other at the next node, progressing through the list.
3. **Removing duplicates from a sorted array**: One pointer keeps track of the unique elements, and the other traverses the array.
4. **Merging two sorted arrays**: Two pointers are used to iterate through the arrays and merge them.
## Example 1: Finding Pairs with a Given Sum
### Problem Statement
Given a sorted array of integers and a target sum, find all pairs in the array that sum up to the target.
### Approach
1. Initialize two pointers: one at the beginning (`left`) and one at the end (`right`) of the array.
2. Calculate the sum of the elements at the `left` and `right` pointers.
3. If the sum is equal to the target, record the pair and move both pointers inward.
4. If the sum is less than the target, move the `left` pointer to the right to increase the sum.
5. If the sum is greater than the target, move the `right` pointer to the left to decrease the sum.
6. Repeat the process until the `left` pointer is not less than the `right` pointer.
### Example Code
```python
def find_pairs_with_sum(arr, target):
left = 0
right = len(arr) - 1
pairs = []
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
pairs.append((arr[left], arr[right]))
left += 1
right -= 1
elif current_sum < target:
left += 1
else:
right -= 1
return pairs
# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 10
result = find_pairs_with_sum(arr, target)
print("Pairs with sum", target, "are:", result)
```
## Example 2: Removing Duplicates from a Sorted Array
### Problem Statement
Given a sorted array, remove the duplicates in place such that each element appears only once and return the new length of the array.
### Approach
1. If the array is empty, return 0.
2. Initialize a slow pointer at the beginning of the array.
3. Use a fast pointer to traverse through the array.
4. Whenever the element at the fast pointer is different from the element at the slow pointer, increment the slow pointer and update the element at the slow pointer with the element at the fast pointer.
5. Continue this process until the fast pointer reaches the end of the array.
6. The slow pointer will indicate the position of the last unique element.
### Example Code
```python
def remove_duplicates(arr):
if not arr:
return 0
slow = 0
for fast in range(1, len(arr)):
if arr[fast] != arr[slow]:
slow += 1
arr[slow] = arr[fast]
return slow + 1
# Example usage
arr = [1, 1, 2, 2, 3, 4, 4, 5]
new_length = remove_duplicates(arr)
print("Array after removing duplicates:", arr[:new_length])
print("New length of array:", new_length)
```
# Advantages of the Two-Pointer Technique
Here are some key benefits of using the two-pointer technique:
## 1. **Improved Time Complexity**
It often reduces the time complexity from O(n^2) to O(n), making it significantly faster for many problems.
### Example
- **Finding pairs with a given sum**: Efficiently finds pairs in O(n) time.
## 2. **Simplicity**
The implementation is straightforward, using basic operations like incrementing or decrementing pointers.
### Example
- **Removing duplicates from a sorted array**: Easy to implement and understand.
## 3. **In-Place Solutions**
Many problems can be solved in place, requiring no extra space beyond the input data.
### Example
- **Reversing a linked list**: Adjusts pointers within the existing nodes.
## 4. **Versatility**
Applicable to a wide range of problems, from arrays and strings to linked lists.
### Example
- **Merging two sorted arrays**: Efficiently merges using two pointers.
## 5. **Efficiency**
Minimizes redundant operations and enhances performance, especially with large data sets.
### Example
- **Partitioning problems**: Efficiently partitions elements with minimal operations.

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.3 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 12 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 12 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 12 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 17 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 12 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 11 KiB

Wyświetl plik

@ -5,5 +5,6 @@
- [Bar Plots in Matplotlib](matplotlib-bar-plots.md)
- [Pie Charts in Matplotlib](matplotlib-pie-charts.md)
- [Line Charts in Matplotlib](matplotlib-line-plots.md)
- [Scatter Plots in Matplotlib](matplotlib-scatter-plot.md)
- [Introduction to Seaborn and Installation](seaborn-intro.md)
- [Getting started with Seaborn](seaborn-basics.md)

Wyświetl plik

@ -0,0 +1,160 @@
# Scatter() plot in matplotlib
* A scatter plot is a type of data visualization that uses dots to show values for two variables, with one variable on the x-axis and the other on the y-axis. It's useful for identifying relationships, trends, and correlations, as well as spotting clusters and outliers.
* The dots on the plot shows how the variables are related. A scatter plot is made with the matplotlib library's `scatter() method`.
## Syntax
**Here's how to write code for the `scatter() method`:**
```
matplotlib.pyplot.scatter (x_axis_value, y_axis_value, s = None, c = None, vmin = None, vmax = None, marker = None, cmap = None, alpha = None, linewidths = None, edgecolors = None)
```
## Prerequisites
Scatter plots can be created in Python with Matplotlib's pyplot library. To build a Scatter plot, first import matplotlib. It is a standard convention to import Matplotlib's pyplot library as plt.
```
import matplotlib.pyplot as plt
```
## Creating a simple Scatter Plot
With Pyplot, you can use the `scatter()` function to draw a scatter plot.
The `scatter()` function plots one dot for each observation. It needs two arrays of the same length, one for the values of the x-axis, and one for values on the y-axis:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
```
When executed, this will show the following Scatter plot:
![Basic line Chart](images/simple_scatter.png)
## Compare Plots
In a scatter plot, comparing plots involves examining multiple sets of points to identify differences or similarities in patterns, trends, or correlations between the data sets.
```
import matplotlib.pyplot as plt
import numpy as np
#day one, the age and speed of 13 cars:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
#day two, the age and speed of 15 cars:
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y)
plt.show()
```
When executed, this will show the following Compare Scatter plot:
![Compare Plots](images/scatter_compare.png)
## Colors in Scatter plot
You can set your own color for each scatter plot with the `color` or the `c` argument:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y, color = 'hotpink')
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y, color = '#88c999')
plt.show()
```
When executed, this will show the following Colors Scatter plot:
![Colors in Scatter plot](images/scatter_color.png)
## Color Each Dot
You can even set a specific color for each dot by using an array of colors as value for the `c` argument:
``Note: You cannot use the `color` argument for this, only the `c` argument.``
```
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray","cyan","magenta"])
plt.scatter(x, y, c=colors)
plt.show()
```
When executed, this will show the following Color Each Dot:
![Color Each Dot](images/scatter_coloreachdot.png)
## ColorMap
The Matplotlib module has a number of available colormaps.
A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.
Here is an example of a colormap:
![ColorMap](images/img_colorbar.png)
This colormap is called 'viridis' and as you can see it ranges from 0, which is a purple color, up to 100, which is a yellow color.
## How to Use the ColorMap
You can specify the colormap with the keyword argument `cmap` with the value of the colormap, in this case `'viridis'` which is one of the built-in colormaps available in Matplotlib.
In addition you have to create an array with values (from 0 to 100), one value for each point in the scatter plot:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.scatter(x, y, c=colors, cmap='viridis')
plt.show()
```
When executed, this will show the following Scatter ColorMap:
![Scatter ColorMap](images/scatter_colormap1.png)
You can include the colormap in the drawing by including the `plt.colorbar()` statement:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.scatter(x, y, c=colors, cmap='viridis')
plt.colorbar()
plt.show()
```
When executed, this will show the following Scatter ColorMap using `plt.colorbar()`:
![Scatter ColorMap1](images/scatter_colormap2.png)