Skip to content

Commit 48664ae

Browse files
Merge branch 'animator:main' into main
2 parents 9a50413 + 225d5b1 commit 48664ae

36 files changed

+1614
-25
lines changed

contrib/database/index.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
# List of sections
22

33
- [Introduction to MySQL and Queries](intro_mysql_queries.md)
4+
- [SQLAlchemy and Aggregation Functions](sqlalchemy-aggregation.md)
+123
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
# SQLAlchemy
2+
SQLAlchemy is a powerful and flexible SQL toolkit and Object-Relational Mapping (ORM) library for Python. It is a versatile library that bridges the gap between Python applications and relational databases.
3+
4+
SQLAlchemy allows the user to write database-agnostic code that can work with a variety of relational databases such as SQLite, MySQL, PostgreSQL, Oracle, and Microsoft SQL Server. The ORM layer in SQLAlchemy allows developers to map Python classes to database tables. This means you can interact with your database using Python objects instead of writing raw SQL queries.
5+
6+
## Setting up the Environment
7+
* Python and MySQL Server must be installed and configured.
8+
* The library: **mysql-connector-python** and **sqlalchemy** must be installed.
9+
10+
```bash
11+
pip install sqlalchemy mysql-connector-python
12+
```
13+
14+
* If not installed, you can install them using the above command in terminal,
15+
16+
## Establishing Connection with Database
17+
18+
* Create a connection with the database using the following code snippet:
19+
```python
20+
from sqlalchemy import create_engine
21+
from sqlalchemy.orm import declarative_base
22+
from sqlalchemy.orm import sessionmaker
23+
24+
DATABASE_URL = 'mysql+mysqlconnector://root:12345@localhost/gssoc'
25+
26+
engine = create_engine(DATABASE_URL)
27+
Session = sessionmaker(bind=engine)
28+
session = Session()
29+
30+
Base = declarative_base()
31+
```
32+
33+
* The connection string **DATABASE_URL** is passed as an argument to **create_engine** function which is used to create a connection to the database. This connection string contains the database credentials such as the database type, username, password, and database name.
34+
* The **sessionmaker** function is used to create a session object which is used to interact with the database
35+
* The **declarative_base** function is used to create a base class for all the database models. This base class is used to define the structure of the database tables.
36+
37+
## Creating Tables
38+
39+
* The following code snippet creates a table named **"products"** in the database:
40+
```python
41+
from sqlalchemy import Column, Integer, String, Float
42+
43+
class Product(Base):
44+
__tablename__ = 'products'
45+
id = Column(Integer, primary_key=True)
46+
name = Column(String(50))
47+
category = Column(String(50))
48+
price = Column(Float)
49+
quantity = Column(Integer)
50+
51+
Base.metadata.create_all(engine)
52+
```
53+
54+
* The **Product class** inherits from **Base**, which is a base class for all the database models.
55+
* The **Base.metadata.create_all(engine)** statement is used to create the table in the database. The engine object is a connection to the database that was created earlier.
56+
57+
## Inserting Data for Aggregation Functions
58+
59+
* The following code snippet inserts data into the **"products"** table:
60+
```python
61+
products = [
62+
Product(name='Laptop', category='Electronics', price=1000, quantity=50),
63+
Product(name='Smartphone', category='Electronics', price=700, quantity=150),
64+
Product(name='Tablet', category='Electronics', price=400, quantity=100),
65+
Product(name='Headphones', category='Accessories', price=100, quantity=200),
66+
Product(name='Charger', category='Accessories', price=20, quantity=300),
67+
]
68+
69+
session.add_all(products)
70+
session.commit()
71+
```
72+
73+
* A list of **Product** objects is created. Each Product object represents a row in the **products table** in the database.
74+
* The **add_all** method of the session object is used to add all the Product objects to the session. This method takes a **list of objects as an argument** and adds them to the session.
75+
* The **commit** method of the session object is used to commit the changes made to the database.
76+
77+
## Aggregation Functions
78+
79+
SQLAlchemy provides functions that correspond to SQL aggregation functions and are available in the **sqlalchemy.func module**.
80+
81+
### COUNT
82+
83+
The **COUNT** function returns the number of rows in a result set. It can be demonstrated using the following code snippet:
84+
```python
85+
from sqlalchemy import func
86+
87+
total_products = session.query(func.count(Product.id)).scalar()
88+
print(f'Total products: {total_products}')
89+
```
90+
91+
### SUM
92+
93+
The **SUM** function returns the sum of all values in a column. It can be demonstrated using the following code snippet:
94+
```python
95+
total_price = session.query(func.sum(Product.price)).scalar()
96+
print(f'Total price of all products: {total_price}')
97+
```
98+
99+
### AVG
100+
101+
The **AVG** function returns the average of all values in a column. It can be demonstrated by the following code snippet:
102+
```python
103+
average_price = session.query(func.avg(Product.price)).scalar()
104+
print(f'Average price of products: {average_price}')
105+
```
106+
107+
### MAX
108+
109+
The **MAX** function returns the maximum value in a column. It can be demonstrated using the following code snippet :
110+
```python
111+
max_price = session.query(func.max(Product.price)).scalar()
112+
print(f'Maximum price of products: {max_price}')
113+
```
114+
115+
### MIN
116+
117+
The **MIN** function returns the minimum value in a column. It can be demonstrated using the following code snippet:
118+
```python
119+
min_price = session.query(func.min(Product.price)).scalar()
120+
print(f'Minimum price of products: {min_price}')
121+
```
122+
123+
In general, the aggregation functions can be implemented by utilising the **session** object to execute the desired query on the table present in a database using the **query()** method. The **scalar()** method is called on the query object to execute the query and return a single value

contrib/ds-algorithms/index.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# List of sections
22

3+
- [Time & Space Complexity](time-space-complexity.md)
34
- [Queues in Python](Queues.md)
45
- [Graphs](graph.md)
56
- [Sorting Algorithms](sorting-algorithms.md)

contrib/ds-algorithms/recursion.md

+44-24
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
When a function calls itself to solve smaller instances of the same problem until a specified condition is fulfilled is called recursion. It is used for tasks that can be divided into smaller sub-tasks.
44

5-
# How Recursion Works
5+
## How Recursion Works
66

77
To solve a problem using recursion we must define:
88
- Base condition :- The condition under which recursion ends.
@@ -17,43 +17,63 @@ When a recursive function is called, the following sequence of events occurs:
1717
- Stack Management: Each recursive call is placed on the call stack. The stack keeps track of each function call, its argument, and the point to return to once the call completes.
1818
- Unwinding the Stack: When the base case is eventually met, the function returns a value, and the stack starts unwinding, returning values to previous function calls until the initial call is resolved.
1919

20-
# What is Stack Overflow in Recursion
20+
## Python Code: Factorial using Recursion
2121

22-
Stack overflow is an error that occurs when the call stack memory limit is exceeded. During execution of recursion calls they are simultaneously stored in a recursion stack waiting for the recursive function to be completed. Without a base case, the function would call itself indefinitely, leading to a stack overflow.
22+
```python
23+
def fact(n):
24+
if n == 0 or n == 1:
25+
return 1
26+
return n * fact(n - 1)
27+
28+
if __name__ == "__main__":
29+
n = int(input("Enter a positive number: "))
30+
print("Factorial of", n, "is", fact(n))
31+
```
2332

24-
# Example
33+
### Explanation
2534

26-
- Factorial of a Number
35+
This Python script calculates the factorial of a given number using recursion.
2736

28-
The factorial of i natural numbers is nth integer multiplied by factorial of (i-1) numbers. The base case is if i=0 we return 1 as factorial of 0 is 1.
29-
30-
```python
31-
def factorial(i):
32-
#base case
33-
if i==0 :
34-
return 1
35-
#recursive case
36-
else :
37-
return i * factorial(i-1)
38-
i = 6
39-
print("Factorial of i is :", factorial(i)) # Output- Factorial of i is :720
40-
```
41-
# What is Backtracking
37+
- **Function `fact(n)`:**
38+
- The function takes an integer `n` as input and calculates its factorial.
39+
- It checks if `n` is 0 or 1. If so, it returns 1 (since the factorial of 0 and 1 is 1).
40+
- Otherwise, it returns `n * fact(n - 1)`, which means it recursively calls itself with `n - 1` until it reaches either 0 or 1.
41+
42+
- **Main Section:**
43+
- The main section prompts the user to enter a positive number.
44+
- It then calls the `fact` function with the input number and prints the result.
45+
46+
#### Example : Let n = 4
47+
48+
The recursion unfolds as follows:
49+
1. When `fact(4)` is called, it computes `4 * fact(3)`.
50+
2. Inside `fact(3)`, it computes `3 * fact(2)`.
51+
3. Inside `fact(2)`, it computes `2 * fact(1)`.
52+
4. `fact(1)` returns 1 (`if` statement executes), which is received by `fact(2)`, resulting in `2 * 1` i.e. `2`.
53+
5. Back to `fact(3)`, it receives the value from `fact(2)`, giving `3 * 2` i.e. `6`.
54+
6. `fact(4)` receives the value from `fact(3)`, resulting in `4 * 6` i.e. `24`.
55+
7. Finally, `fact(4)` returns 24 to the main function.
56+
57+
#### So, the result is 24.
58+
59+
#### What is Stack Overflow in Recursion?
60+
61+
Stack overflow is an error that occurs when the call stack memory limit is exceeded. During execution of recursion calls they are simultaneously stored in a recursion stack waiting for the recursive function to be completed. Without a base case, the function would call itself indefinitely, leading to a stack overflow.
62+
63+
## What is Backtracking
4264

4365
Backtracking is a recursive algorithmic technique used to solve problems by exploring all possible solutions and discarding those that do not meet the problem's constraints. It is particularly useful for problems involving combinations, permutations, and finding paths in a grid.
4466

45-
# How Backtracking Works
67+
## How Backtracking Works
4668

4769
- Incremental Solution Building: Solutions are built one step at a time.
4870
- Feasibility Check: At each step, a check is made to see if the current partial solution is valid.
4971
- Backtracking: If a partial solution is found to be invalid, the algorithm backtracks by removing the last added part of the solution and trying the next possibility.
5072
- Exploration of All Possibilities: The process continues recursively, exploring all possible paths, until a solution is found or all possibilities are exhausted.
5173

52-
# Example
53-
54-
- Word Search
74+
## Example: Word Search
5575

56-
Given a 2D grid of characters and a word, determine if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
76+
Given a 2D grid of characters and a word, determine if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
5777

5878
Algorithm for Solving the Word Search Problem with Backtracking:
5979
- Start at each cell: Attempt to find the word starting from each cell.

0 commit comments

Comments
 (0)