diff --git a/_config.yml b/_config.yml new file mode 100644 index 000000000..5fd5919b4 --- /dev/null +++ b/_config.yml @@ -0,0 +1,18 @@ +title: CodeHarborHub +description: >- # A longer description + CodeHarborHub is a platform for sharing and learning Web Development, Programming, and Software Development. +author: Ajay Dhangar +email: ajaydhangar49@gmail.com +baseurl: "/" # Leave empty for GitHub Pages +url: "https://codeharborhub.github.io" # Replace with your GitHub Pages URL + +# Build settings +theme: minima # Choose a Jekyll theme (e.g., minima, cayman, slate, etc.) +plugins: + - jekyll-feed # Enables RSS feed for posts + +# Optional: Custom settings for the theme +markdown: kramdown +highlighter: rouge +permalink: pretty +paginate: 5 # Number of posts per page diff --git a/docs/Nodemailer/HowtoSecure.md b/docs/Nodemailer/HowtoSecure.md deleted file mode 100644 index 38c8a1a8b..000000000 --- a/docs/Nodemailer/HowtoSecure.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -id: nodemailer-secure -title: Nodemailer Security -sidebar_label: Security -sidebar_position: 4 -description: How to secure the password and mail address. -tags: [Node.Js, NodeMailer, env , SMTP ,JavaScript framework] ---- -How to secure the mail address and Password: - -### Environment Variables (Recommended) - -It's good practice to keep your email credentials secure by using environment variables. You can use the `dotenv` package to manage these variables. - -1. **Install the `dotenv` package**: - ```bash - npm install dotenv - ``` - -2. **Create a `.env` file in your project root** and add your credentials: - ``` - EMAIL=your-email@gmail.com - PASSWORD=your-email-password - ``` - -3. **Modify your `sendEmail.js` file to use `dotenv`**: - ```javascript - const nodemailer = require('nodemailer'); - require('dotenv').config(); - - // Create a transporter object - let transporter = nodemailer.createTransport({ - service: 'gmail', - auth: { - user: process.env.EMAIL, - pass: process.env.PASSWORD - } - }); - - // Define email options - let mailOptions = { - from: process.env.EMAIL, - to: 'recipient@example.com', - subject: 'Test Email', - text: 'Hello, this is a test email sent using Nodemailer!', - html: 'Hello, this is a test email sent using Nodemailer!' - }; - - // Send the email - transporter.sendMail(mailOptions, (error, info) => { - if (error) { - return console.log(error); - } - console.log('Email sent: ' + info.response); - }); - ``` - \ No newline at end of file diff --git a/docs/Nodemailer/Introduction.md b/docs/Nodemailer/Introduction.md deleted file mode 100644 index a13edc951..000000000 --- a/docs/Nodemailer/Introduction.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -id: nodemailer-intro -title: Nodemailer -sidebar_label: Introduction -sidebar_position: 1 -description: Nodemailer is a module for Node.js applications that allows you to send emails. -tags: [Node.Js, NodeMailer, env , SMTP ,JavaScript framework] ---- - -Nodemailer is a module for Node.js applications that allows you to send emails. It is designed to be easy to set up and use, providing a straightforward API for sending emails through various email services and SMTP servers. Here are some key features and components of Nodemailer: - -1. **SMTP Support**: Nodemailer supports sending emails using SMTP (Simple Mail Transfer Protocol), allowing you to use your own email server or a third-party service like Gmail, Outlook, or Yahoo Mail. - -2. **Transporters**: A transporter is an object that defines how emails are sent. Nodemailer provides several built-in transport methods, including SMTP, Sendmail, and more. You can also create custom transport methods if needed. - -3. **Email Formatting**: Nodemailer supports both plain text and HTML email bodies, making it easy to create rich, formatted emails. It also supports attachments, inline images, and various encoding methods. - -4. **Authentication**: Nodemailer supports various authentication mechanisms, including OAuth2, making it secure and flexible for different use cases. diff --git a/docs/Nodemailer/Setup.md b/docs/Nodemailer/Setup.md deleted file mode 100644 index a839fc520..000000000 --- a/docs/Nodemailer/Setup.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -id: nodemailer-installation -title: Installation -sidebar_label: Installation -sidebar_position: 2 -description: How to Install Nodemailer. -tags: [Node.Js, NodeMailer, env , SMTP ,JavaScript framework] ---- - -To install Nodemailer in your Node.js project, follow these steps: - -### Step 1: Initialize Your Project - -First, make sure you have Node.js and npm installed. If not, you can download and install them from the [official Node.js website](https://nodejs.org/). - -1. **Create a new directory for your project** (if you don't already have one): - ```bash - mkdir my-project - cd my-project - ``` - -2. **Initialize a new Node.js project**: - ```bash - npm init -y - ``` - -### Step 2: Install Nodemailer - -You can install Nodemailer using npm. Run the following command in your project directory: - -```bash -npm install nodemailer -``` - -This command will install Nodemailer and add it to your `package.json` file as a dependency. - -### Setp 3: How Import - -Two methods to import the package - -- In node & Express Js -```bash -const nodemailer=require('nodemailer') -``` - -- In another ES6 method - -```bash -import nodemailer from 'nodemailer' -``` - - diff --git a/docs/Nodemailer/_category_.json b/docs/Nodemailer/_category_.json deleted file mode 100644 index 04fecbfe4..000000000 --- a/docs/Nodemailer/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Nodemailer", - "position": 25, - "link": { - "type": "generated-index", - "description": "Nodemailer is a module for Node.js applications that allows you to send emails. It is designed to be easy to set up and use." - } - } \ No newline at end of file diff --git a/docs/dsa/Hash/_category_.json b/docs/dsa/Hash/_category_.json deleted file mode 100644 index 93424d3c3..000000000 --- a/docs/dsa/Hash/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Hash", - "position": 15, - "link": { - "type": "generated-index", - "description": "Hash is a data structure that maps keys to values. It uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found." - } -} diff --git a/docs/dsa/Hash/hash.md b/docs/dsa/Hash/hash.md deleted file mode 100644 index 398b6dd33..000000000 --- a/docs/dsa/Hash/hash.md +++ /dev/null @@ -1,150 +0,0 @@ -# Hash in DSA (Data Structures and Algorithms) - -Hash in DSA (Data Structures and Algorithms) is a function that takes an input (or "key") and produces a fixed-size string of characters, which is typically a unique representation of the input. Hash functions are commonly used in various applications, such as data indexing, password storage, and digital signatures. - -![alt text](image.png) - -- A hash function takes an input and applies a mathematical algorithm to generate a hash value. The hash value is a fixed-size string that is unique to the input data. It is important to note that even a small change in the input data will result in a completely different hash value. - -![alt text](image-1.png) - -- Hash functions are designed to minimize the occurrence of hash collisions, where two different inputs produce the same hash value. However, it is still possible for collisions to occur due to the limited size of the hash value compared to the potentially infinite input space. - -- One common use of hash functions is in data indexing. Hash tables, also known as hash maps, use hash functions to map keys to specific locations in memory, allowing for efficient retrieval and storage of data. - -Hash functions are also used in password storage. Instead of storing passwords in plain text, they are hashed and the hash value is stored. When a user enters their password, it is hashed and compared to the stored hash value for authentication. - - - -Hash functions are an integral part of digital signatures. They are used to generate a unique hash value for a document or message, which is then encrypted with the sender's private key. The recipient can verify the integrity of the message by decrypting the hash value with the sender's public key and comparing it to the computed hash value of the received message. - -Overall, hash functions play a crucial role in various applications by providing a unique representation of data, enabling efficient data retrieval, ensuring data integrity, and enhancing security. - -## Implementing Hash Functions in Different Programming Languages - -Here's a basic example of how to implement a hash function in different programming languages: - -Python: -```python -import hashlib - -def hash_string(input_string): - hash_object = hashlib.sha256(input_string.encode()) - return hash_object.hexdigest() - -input_string = "Hello, World!" -hashed_string = hash_string(input_string) -print(hashed_string) -``` -Output: `2ef7bde608ce5404e97d5f042f95f89f1c232871` - -Java: -```java -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -public class HashExample { - public static String hashString(String inputString) throws NoSuchAlgorithmException { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - byte[] hashBytes = md.digest(inputString.getBytes()); - StringBuilder sb = new StringBuilder(); - for (byte b : hashBytes) { - sb.append(String.format("%02x", b)); - } - return sb.toString(); - } - - public static void main(String[] args) throws NoSuchAlgorithmException { - String inputString = "Hello, World!"; - String hashedString = hashString(inputString); - System.out.println(hashedString); - } -} -``` -Output: `2ef7bde608ce5404e97d5f042f95f89f1c232871` - -C++: -```cpp -#include -#include - -std::string hashString(const std::string& inputString) { - unsigned char hash[SHA256_DIGEST_LENGTH]; - SHA256_CTX sha256; - SHA256_Init(&sha256); - SHA256_Update(&sha256, inputString.c_str(), inputString.length()); - SHA256_Final(hash, &sha256); - std::stringstream ss; - for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { - ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i]; - } - return ss.str(); -} - -int main() { - std::string inputString = "Hello, World!"; - std::string hashedString = hashString(inputString); - std::cout << hashedString << std::endl; - return 0; -} -``` -Output: `2ef7bde608ce5404e97d5f042f95f89f1c232871` - -Please note that these examples use the SHA-256 hash function as an illustration. Different hash functions may be used depending on the specific requirements of your application. - -## Example Questions with Code in Python - -Here are some example questions with code in Python to help you practice implementing hash functions: - -1. **Question:** Write a Python function to calculate the MD5 hash of a given string. - -```python -import hashlib - -def calculate_md5_hash(input_string): - hash_object = hashlib.md5(input_string.encode()) - return hash_object.hexdigest() - -input_string = "Hello, World!" -md5_hash = calculate_md5_hash(input_string) -print(md5_hash) -``` - -**Output:** `3e25960a79dbc69b674cd4ec67a72c62` - -2. **Question:** Implement a Python program to find the SHA-1 hash of a file. - -```python -import hashlib - -def calculate_sha1_hash(file_path): - sha1_hash = hashlib.sha1() - with open(file_path, 'rb') as file: - for chunk in iter(lambda: file.read(4096), b''): - sha1_hash.update(chunk) - return sha1_hash.hexdigest() - -file_path = "path/to/file.txt" -sha1_hash = calculate_sha1_hash(file_path) -print(sha1_hash) -``` - -**Output:** `2ef7bde608ce5404e97d5f042f95f89f1c232871` - -3. **Question:** Write a Python function to generate a random salt value for password hashing. - -```python -import os -import hashlib - -def generate_salt(): - salt = os.urandom(16) - return salt.hex() - -salt = generate_salt() -print(salt) -``` - -**Output:** `a5f7b9c8d7e6f5a4b3c2d1e0f9e8d7c6` - -Remember to customize these examples based on your specific requirements and use appropriate hash functions for your application. diff --git a/docs/dsa/Hash/image-1.png b/docs/dsa/Hash/image-1.png deleted file mode 100644 index c0b6d612e..000000000 Binary files a/docs/dsa/Hash/image-1.png and /dev/null differ diff --git a/docs/dsa/Hash/image.png b/docs/dsa/Hash/image.png deleted file mode 100644 index fb86e722e..000000000 Binary files a/docs/dsa/Hash/image.png and /dev/null differ diff --git a/docs/dsa/Heaps/_category_.json b/docs/dsa/Heaps/_category_.json deleted file mode 100644 index c9f03476e..000000000 --- a/docs/dsa/Heaps/_category_.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "label": "Heaps", - "position": 10, - "link": { - "type": "generated-index", - "description": "Heaps are a type of binary tree-based data structure that satisfy the heap property. They are commonly used to implement priority queues and efficiently find the maximum or minimum element. Heaps can be either max heaps or min heaps, depending on whether the parent nodes are greater or smaller than their children. Operations like insertion, deletion, and retrieval of the maximum or minimum element can be performed efficiently on heaps." - } - - } - - - diff --git a/docs/dsa/Heaps/heaps.md b/docs/dsa/Heaps/heaps.md deleted file mode 100644 index 8035806d3..000000000 --- a/docs/dsa/Heaps/heaps.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -id: heaps-in-dsa -title: Heaps Data Structure -sidebar_label: Heaps -sidebar_position: 1 -description: "Heaps are a type of binary tree-based data structure commonly used in computer science. They are often used to implement priority queues, where elements with higher priority are dequeued first. Heaps have two main variations: max heaps, where the parent node is always greater than or equal to its children, and min heaps, where the parent node is always less than or equal to its children. Heaps have efficient insertion and deletion operations, making them suitable for applications that require efficient priority-based processing." -tags: [dsa, data-structures, heaps] ---- - - - -## Python - Heaps - -Heap is a special tree structure in which each parent node is less than or equal to its child node. Then it is called a Min Heap. If each parent node is greater than or equal to its child node then it is called a max heap. It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing. - -A detailed discussion on heaps is available in our website here. Please study it first if you are new to heap data structure. In this chapter we will see the implementation of heap data structure using python. - -![alt text](image.png) -## Create a Heap - -A heap is created by using python’s inbuilt library named heapq. This library has the relevant functions to carry out various operations on heap data structure. Below is a list of these functions. - -- heapify − This function converts a regular list to a heap. In the resulting heap the smallest element gets pushed to the index position 0. But rest of the data elements are not necessarily sorted. - -- heappush − This function adds an element to the heap without altering the current heap. - -- heappop − This function returns the smallest data element from the heap. - -- heapreplace − This function replaces the smallest data element with a new value supplied in the function. - -## Creating a Heap -A heap is created by simply using a list of elements with the heapify function. In the below example we supply a list of elements and the heapify function rearranges the elements bringing the smallest element to the first position. - - -**Python - Heaps** - -Heap is a special tree structure in which each parent node is less than or equal to its child node. Then it is called a Min Heap. - -If each parent node is greater than or equal to its child node then it is called a max heap. - -It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing. - -A detailed discussion on heaps is available in our website here. Please study it first if you are new to heap data structure. In this chapter we will see the implementation of heap data structure using python. - -**Example** -``` python -import heapq - -H = [21,1,45,78,3,5] -# Use heapify to rearrange the elements -heapq.heapify(H) -print(H) -``` - -## Output -When the above code is executed, it produces the following result − -``` python -[1, 3, 5, 78, 21, 45] -``` -## Inserting into heap - -Inserting a data element to a heap always adds the element at the last index. But you can apply heapify function again to bring the newly added element to the first index only if it smallest in value. In the below example we insert the number 8. - -**Example** - -``` python -import heapq - -H = [21,1,45,78,3,5] -# Covert to a heap -heapq.heapify(H) -print(H) - -# Add element -heapq.heappush(H,8) -print(H) -``` - -## Output - -When the above code is executed, it produces the following result − -```python -[1, 3, 5, 78, 21, 45] -[1, 3, 5, 78, 21, 45, 8] -``` -## Removing from heap - -You can remove the element at first index by using this function. In the below example the function will always remove the element at the index position 1. - -**Example** -```python -import heapq - -H = [21,1,45,78,3,5] -# Create the heap - -heapq.heapify(H) -print(H) - -# Remove element from the heap -heapq.heappop(H) - -print(H) -Output -When the above code is executed, it produces the following result − -```python -[1, 3, 5, 78, 21, 45] -[3, 21, 5, 78, 45] -``` -## Replacing in a Heap - -The heap replace function always removes the smallest element of the heap and inserts the new incoming element at some place not fixed by any order. - -**Example** -``` python -import heapq - -H = [21,1,45,78,3,5] -# Create the heap - -heapq.heapify(H) -print(H) - -# Replace an element -heapq.heapreplace(H,6) -print(H) -``` - -## Output -When the above code is executed, it produces the following result − -```python -[1, 3, 5, 78, 21, 45] -[3, 6, 5, 78, 21, 45] -``` \ No newline at end of file diff --git a/docs/dsa/Heaps/image.png b/docs/dsa/Heaps/image.png deleted file mode 100644 index 1e9381c81..000000000 Binary files a/docs/dsa/Heaps/image.png and /dev/null differ diff --git a/docs/dsa/Kadanes.md b/docs/dsa/Kadanes.md deleted file mode 100644 index e4eda5b2d..000000000 --- a/docs/dsa/Kadanes.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -id: Kadanes-Algorithm -title: Kadanes Algorithm -sidebar_label: KadanesAlgorithm -sidebar_position: 2 -description: "Kadane's Algorithm efficiently finds the maximum sum contiguous subarray in a one-dimensional array. It's a dynamic programming technique named after its creator, Jay Kadane." ---- -## Kadane's Algorithm: - -- **Purpose**: Finds the maximum sum of a contiguous subarray. -- **Time Complexity**: $O(n)$ -- **Space Complexity**: O(1) -- **Use Case**: Optimal for solving maximum subarray sum problems in linear time. -### Simple Explanation -Kadane's Algorithm: - -1. **Initialize**: - - Set `maxSum` to a very small number (e.g., negative infinity). - - Set `currentSum` to 0. - -2. **Iterate Through the Array**: - - For each element in the array: - - Add the element to `currentSum`. - - Update `maxSum` if `currentSum` is greater than `maxSum`. - - If `currentSum` becomes negative, reset it to 0. - -3. **Result**: - - The value of `maxSum` at the end of the iteration is the maximum sum of any contiguous subarray. -### Code - -Input: arr = {-2,-3,4,-1,-2,1,5,-3} - -Output: 7 - -Explanation: The subarray {4,-1, -2, 1, 5} has the largest sum 7. - -### Python -```py - - def max_sub_array(nums): - max_sum = float('-inf') - current_sum = 0 - - for num in nums: - # Add the current number to the current_sum - current_sum += num - # Update max_sum if current_sum is greater - max_sum = max(max_sum, current_sum) - # Reset current_sum to 0 if it drops below 0 - if current_sum < 0: - current_sum = 0 - - return max_sum -``` - -### C++ -```cpp - // Kadane's Algorithm to find the maximum sum of a contiguous subarray - - #include - #include - #include - #include - - int maxSubArray(const std::vector& nums) { - // Initialize max_sum to the lowest possible value and current_sum to 0 - int max_sum = INT_MIN; - int current_sum = 0; - - for (int num : nums) { - // Add the current number to the current_sum - current_sum += num; - // Update max_sum if current_sum is greater - max_sum = std::max(max_sum, current_sum); - // Reset current_sum to 0 if it drops below 0 - if (current_sum < 0) { - current_sum = 0; - } - } - - return max_sum; - } -``` - -### Explanation -Explanation: - -#### Initialization: - - -`max_sum` is initialized to `INT_MIN` to handle arrays with all negative numbers. - - -`current_sum` starts at `0`. - -#### Iteration: - - -Traverse through each number in the array: - - -Add the number to `current_sum`. - - -Update `max_sum` to be the maximum of `max_sum` and `current_sum`. - - -If `current_sum` becomes negative, reset it to `0` to start a new subarray. - - diff --git a/docs/dsa/Matrix/_category_.json b/docs/dsa/Matrix/_category_.json deleted file mode 100644 index d8a0abc0d..000000000 --- a/docs/dsa/Matrix/_category_.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "label": "Matrix", - "position": 9, - "link": { - "type": "generated-index", - "description": "In data structures and algorithms (DSA), a matrix is a two-dimensional array consisting of rows and columns. It is often used to represent a grid-like structure or a table of values. Matrices are commonly used in various algorithms and mathematical operations, such as matrix multiplication, graph algorithms, image processing, and more. They provide a convenient way to organize and manipulate data in a structured manner." - } - } - \ No newline at end of file diff --git a/docs/dsa/Matrix/image.png b/docs/dsa/Matrix/image.png deleted file mode 100644 index 71f730ab9..000000000 Binary files a/docs/dsa/Matrix/image.png and /dev/null differ diff --git a/docs/dsa/Matrix/matrix.md b/docs/dsa/Matrix/matrix.md deleted file mode 100644 index 27040b09c..000000000 --- a/docs/dsa/Matrix/matrix.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -id: matrix-in-dsa -title: Matrix Data Structure -sidebar_label: Matrix -sidebar_position: 1 -description: "A matrix is a two-dimensional data structure consisting of rows and columns, where each element is identified by its row and column index. It is commonly used in various fields, including mathematics, computer science, and data analysis, to represent and manipulate structured data. " -tags: [dsa, data-structures, Matrix] ---- - -**Matrix Data Structure** is a two-dimensional array arranged in rows and columns. It is commonly used to represent mathematical matrices and is fundamental in various fields like mathematics, computer graphics, and data processing. Matrices allow for efficient storage and manipulation of data in a structured format - -## Components of Matrix Data Structure -- Size: A matrix has a specific size, defined by its number of rows and columns. -- Element: A matrix’s row and column indices serve to identify each entry, which is referred to as an element. -- Operations: Scalar multiplication and the operations of addition, subtraction, and multiplication on matrices are also supported. -- Determinant: A square matrix’s determinant is a scalar number that may be used to solve systems of linear equations and carry out other linear algebraic operations. -- Inverse: If a square matrix has an inverse, it may be used to solve linear equation systems and carry out other linear algebraic operations. -- Transpose: By flipping a matrix along its main diagonal and switching the rows and columns, you may create the transpose of the matrix. -- Rank: In many applications, including the solution of linear equations and linear regression analysis, the rank of a matrix—a measure of its linearly independent rows or columns—is utilized - -## Applications of Matrix Data Structure -- Linear Algebra: Matrices are widely used in linear algebra, a branch of mathematics that deals with linear equations, vector spaces, and linear transformations. Matrices are used to represent linear equations and to solve systems of linear equations. -- Optimization: Matrices are used in optimization problems, such as linear programming, to represent the constraints and objective functions of the problem. -- Statistics: Matrices are used in statistics to represent data and to perform operations such as correlation and regression. -- Signal Processing: Matrices are used in signal processing to represent signals and to perform operations such as filtering and transformation. -- Network Analysis: Matrices are used in network analysis to represent graphs and to perform operations such as finding the shortest path between two nodes. -- Quantum Mechanics: Matrices are used in quantum mechanics to represent states and operations in quantum systems. - - - -## Representation of Matrix Data Structure: - -![alt text](image.png) - -As you can see from the above image, the elements are organized in rows and columns. As shown in the above image the cell x[0][0] is the first element of the first row and first column. The value in the first square bracket represents the row number and the value inside the second square bracket represents the column number. (i.e, x[row][column]). - -## Declaration of Matrix Data Structure : - -Declaration of a Matrix or two-dimensional array is very much similar to that of a one-dimensional array, given as follows. -``` python -# Defining number of rows and columns in matrix -number_of_rows = 3 -number_of_columns = 3 -# Declaring a matrix of size 3 X 3, and initializing it with value zero -rows, cols = (3, 3) -arr = [[0]*cols]*rows -print(arr) -``` - -## Initializing Matrix Data Structure: -In initialization, we assign some initial value to all the cells of the matrix. Below is the implementation to initialize a matrix in different languages: - -``` python -# Initializing a 2-D array with values -arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; -``` - -## Operations on Matrix Data Structure: - -We can perform a variety of operations on the Matrix Data Structure. Some of the most common operations are: - -- Access elements of Matrix -- Traversal of a Matrix -- Searching in a Matrix -- Sorting a Matrix - -## 1. Access elements of Matrix Data Structure: - -Like one-dimensional arrays, matrices can be accessed randomly by using their indices to access the individual elements. A cell has two indices, one for its row number, and the other for its column number. We can use arr[i][j] to access the element which is at the ith row and jth column of the matrix. - -```python -# Initializing a 2-D array with values -arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] - -# Accessing elements of 2-D array -print("First element of first row:", arr[0][0]) -print("Third element of second row:", arr[1][2]) -print("Second element of third row:", arr[2][1]) -``` - -## 2. Traversal of a Matrix Data Structure: -We can traverse all the elements of a matrix or two-dimensional array by using two for-loops. - -``` python -arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] -``` -```python -# Traversing over all the rows -for i in range(0, 3): - # Traversing over all the columns of each row - for j in range(0, 4): - print(arr[i][j], end=" ") - print("") -``` - -Output -``` python -1 2 3 4 -5 6 7 8 -9 10 11 12 -``` -## 3. Searching in a Matrix Data Structure: - -We can search an element in a matrix by traversing all the elements of the matrix. - -Below is the implementation to search an element in a matrix: - -```python -# Python code for above approach -def searchInMatrix(arr, x): - # m=4,n=5 - for i in range(0, 4): - for j in range(0, 5): - if(arr[i][j] == x): - return 1 - return - -x = 8 -arr = [[0, 6, 8, 9, 11], - [20, 22, 28, 29, 31], - [36, 38, 50, 61, 63], - [64, 66, 100, 122, 128]] -if(searchInMatrix(arr, x)): - print("YES") -else: - print("NO") - - # This code is contributed by dhairyagothi. -``` - -Output -```python -YES -``` - -## 4. Sorting Matrix Data Structure: -We can sort a matrix in two-ways: - -- Sort the matrix row-wise -- Sort the matrix column-wise - -## Advantages of Matrix Data Structure: -- It helps in 2D Visualization. -- It stores multiple elements of the same type using the same name. -- It enables access to items at random. -- Any form of data with a fixed size can be stored. -- It is easy to implement. - -## Disadvantages of Matrix Data Structure: -- Space inefficient when we need to store very few elements in the matrix. -- The matrix size should be needed beforehand. -- Insertion and deletion operations are costly if shifting occurs. -- Resizing a matrix is time-consuming. diff --git a/docs/dsa/Matrix/problems-matrix.md b/docs/dsa/Matrix/problems-matrix.md deleted file mode 100644 index 1801abef2..000000000 --- a/docs/dsa/Matrix/problems-matrix.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -id: matrix-problems -title: Matrix Practice Problems -sidebar_label: Matrix Practice Problems -sidebar_position: 2 -description: "A matrix is a two-dimensional data structure consisting of rows and columns, where each element is identified by its row and column index. It is commonly used in various fields, including mathematics, computer science, and data analysis, to represent and manipulate structured data. " -tags: [dsa, data-structures, Matrix ] ---- - -## Sort the given matrix - -Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that the matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where ```1 <= i <= n-1```, the first element of row ‘i’ is greater than or equal to the last element of row ‘i-1’. - -**Examples:** -``` -Input : mat[][] = { {5, 4, 7}, - {1, 3, 8}, - {2, 9, 6} } -Output : 1 2 3 - 4 5 6 - 7 8 9 -``` -## Solution -```python -# Python program for the above approach -# driver code -v = [[5,4,7], [1,3,8], [2,9,6]] -n = len(v) - -x = [] -for i in range(n): - for j in range(n): - x.append(v[i][j]) - -x.sort() -k = 0 -for i in range(n): - for j in range(n): - v[i][j] = x[k] - k += 1 - -print("Sorted Matrix will be: ") -for i in range(n): - for j in range(n): - print(v[i][j], end=" ") - print("") - -# THIS CODE IS CONTRIBUTED BY Dhairya Gothi(dhairyagothi) -``` - -## Output -Sorted Matrix Will be: -``` -1 2 3 -4 5 6 -7 8 9 -``` -**Time Complexity:** O(n2log2n), O(n*n) for traversing, and O(n2log2n) for sorting the vector x, which has a size of n2. So overall time complexity is O(n2log2n). -**Auxiliary Space:** O(n*n), For vector. - -## Program for scalar multiplication of a matrix - -Given a matrix and a scalar element k, our task is to find out the scalar product of that matrix. - -**Examples:** -``` -Input : mat[][] = {{2, 3} - {5, 4}} - k = 5 -Output : 10 15 - 25 20 -We multiply 5 with every element. - -Input : 1 2 3 - 4 5 6 - 7 8 9 - k = 4 -Output : 4 8 12 - 16 20 24 - 28 32 36 -The scalar multiplication of a number k(scalar), multiply it on every entry in the matrix. and a matrix A is the matrix kA. - ``` - -```python -# Python 3 program to find the scalar -# product of a matrix - -# Size of given matrix -N = 3 - -def scalarProductMat( mat, k): - - # scalar element is multiplied - # by the matrix - for i in range( N): - for j in range( N): - mat[i][j] = mat[i][j] * k - -# Driver code -if __name__ == "__main__": - - mat = [[ 1, 2, 3 ], - [ 4, 5, 6 ], - [ 7, 8, 9 ]] - k = 4 - - scalarProductMat(mat, k) - - # to display the resultant matrix - print("Scalar Product Matrix is : ") - for i in range(N): - for j in range(N): - print(mat[i][j], end = " ") - print() - -# This code is contributed by dhairya -``` -## Output: -``` -Scalar Product Matrix is : -4 8 12 -16 20 24 -28 32 36 -``` - - -**ime Complexity:** O(n2), - -**Auxiliary Space:** O(1), since no extra space has been taken. - diff --git a/docs/dsa/Queue/_category_.json b/docs/dsa/Queue/_category_.json deleted file mode 100644 index 667dc3fce..000000000 --- a/docs/dsa/Queue/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Queue", - "position": 11, - "link": { - "type": "generated-index", - "description": "A queue is a data structure that follows the First-In-First-Out (FIFO) principle. It is similar to a real-life queue, where the first person to join the queue is the first one to be served. In programming, a queue allows you to add elements to the end and remove elements from the front. This makes it useful for implementing algorithms that require a FIFO ordering, such as breadth-first search. Queues are commonly used in operating systems, networking, and other areas of computer science." - } -} diff --git a/docs/dsa/Queue/image.png b/docs/dsa/Queue/image.png deleted file mode 100644 index c6b3b4639..000000000 Binary files a/docs/dsa/Queue/image.png and /dev/null differ diff --git a/docs/dsa/Queue/queue.md b/docs/dsa/Queue/queue.md deleted file mode 100644 index c1832a4fc..000000000 --- a/docs/dsa/Queue/queue.md +++ /dev/null @@ -1,247 +0,0 @@ ---- -id: queue-in-dsa -title: Queue Data Structure -sidebar_label: Queue -sidebar_position: 1 -description: "A queue is a linear data structure that follows the First In First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed. Queues are used in various applications such as process scheduling, breadth-first search, and more." -tags: [dsa, data-structures, Queue] ---- - -### Introduction to Queue - -A queue is a linear data structure that follows the First In First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed. Queues are used in various applications such as process scheduling, breadth-first search, and more. - -![alt text](image.png) - -### Queue Operations - -1. **Enqueue**: Add an element to the end of the queue. -2. **Dequeue**: Remove the element from the front of the queue. -3. **Peek**: Retrieve the element from the front of the queue without removing it. -4. **isEmpty**: Check if the queue is empty. -5. **Size**: Get the number of elements in the queue. - -### Pseudocode - -#### Basic Operations - -1. **Enqueue**: - - ```text - function enqueue(queue, element): - queue.append(element) - ``` - -2. **Dequeue**: - - ```text - function dequeue(queue): - if isEmpty(queue): - return "Queue Underflow" - return queue.pop(0) - ``` - -3. **Peek**: - - ```text - function peek(queue): - if isEmpty(queue): - return "Queue is empty" - return queue[0] - ``` - -4. **isEmpty**: - - ```text - function isEmpty(queue): - return len(queue) == 0 - ``` - -5. **Size**: - ```text - function size(queue): - return len(queue) - ``` - -### Implementation in Python, C++, and Java - -#### Python Implementation - -```python -class Queue: - def __init__(self): - self.elements = [] - - def enqueue(self, element): - self.elements.append(element) - - def dequeue(self): - if self.is_empty(): - return "Queue Underflow" - return self.elements.pop(0) - - def peek(self): - if self.is_empty(): - return "Queue is empty" - return self.elements[0] - - def is_empty(self): - return len(self.elements) == 0 - - def size(self): - return len(self.elements) - -# Example usage -queue = Queue() -queue.enqueue(10) -queue.enqueue(20) -print(queue.dequeue()) # Output: 10 -print(queue.peek()) # Output: 20 -print(queue.is_empty()) # Output: False -print(queue.size()) # Output: 1 -``` - -#### C++ Implementation - -```cpp -#include -#include - -class Queue { -private: - std::vector elements; - -public: - void enqueue(int element) { - elements.push_back(element); - } - - int dequeue() { - if (is_empty()) { - std::cerr << "Queue Underflow" << std::endl; - return -1; - } - int front = elements.front(); - elements.erase(elements.begin()); - return front; - } - - int peek() { - if (is_empty()) { - std::cerr << "Queue is empty" << std::endl; - return -1; - } - return elements.front(); - } - - bool is_empty() { - return elements.empty(); - } - - int size() { - return elements.size(); - } -}; - -// Example usage -int main() { - Queue queue; - queue.enqueue(10); - queue.enqueue(20); - std::cout << queue.dequeue() << std::endl; // Output: 10 - std::cout << queue.peek() << std::endl; // Output: 20 - std::cout << std::boolalpha << queue.is_empty() << std::endl; // Output: false - std::cout << queue.size() << std::endl; // Output: 1 - return 0; -} -``` - -#### Java Implementation - -```java -import java.util.ArrayList; - -public class Queue { - private ArrayList elements; - - public Queue() { - elements = new ArrayList<>(); - } - - public void enqueue(int element) { - elements.add(element); - } - - public int dequeue() { - if (is_empty()) { - System.out.println("Queue Underflow"); - return -1; - } - return elements.remove(0); - } - - public int peek() { - if (is_empty()) { - System.out.println("Queue is empty"); - return -1; - } - return elements.get(0); - } - - public boolean is_empty() { - return elements.isEmpty(); - } - - public int size() { - return elements.size(); - } - - // Example usage - public static void main(String[] args) { - Queue queue = new Queue(); - queue.enqueue(10); - queue.enqueue(20); - System.out.println(queue.dequeue()); // Output: 10 - System.out.println(queue.peek()); // Output: 20 - System.out.println(queue.is_empty()); // Output: false - System.out.println(queue.size()); // Output: 1 - } -} -``` - -### Complexity - -- **Time Complexity**: - - - Enqueue: $O(1)$ - - Dequeue: $O(1)$ - - Peek: $O(1)$ - - isEmpty: $O(1)$ - - Size: $O(1)$ - -- **Space Complexity**: $O(n)$, where $n$ is the number of elements in the queue. - -### Example - -Consider a queue with the following operations: - -1. Enqueue 10 -2. Enqueue 20 -3. Dequeue -4. Peek -5. Check if empty -6. Get size - -**Operations**: - -- Enqueue 10: Queue becomes [10] -- Enqueue 20: Queue becomes [10, 20] -- Dequeue: Removes 10, Queue becomes [20] -- Peek: Returns 20, Queue remains [20] -- isEmpty: Returns false -- Size: Returns 1 - -### Conclusion - -A queue is a fundamental data structure used in computer science for various applications where the FIFO (First In First Out) principle is required. It is simple to implement and provides efficient operations for adding and removing elements. Understanding and using queues effectively can help solve many algorithmic problems. - diff --git a/docs/dsa/Trees/Trees.md b/docs/dsa/Trees/Trees.md deleted file mode 100644 index 289ac50a8..000000000 --- a/docs/dsa/Trees/Trees.md +++ /dev/null @@ -1,415 +0,0 @@ -# Trees in Data Structures and Algorithms - -A tree is a widely used data structure in computer science that represents a hierarchical structure. It consists of nodes connected by edges, where each node can have zero or more child nodes. Trees are used to represent various real-world scenarios and are essential in many algorithms and data manipulation operations. - -![alt text](image-1.png) - -**Here are some key concepts related to DSA trees:** - -1. **Node**: A node is a fundamental building block of a tree. It contains data and references to its child nodes, if any. In a binary tree, each node can have at most two child nodes, referred to as the left child and the right child. - -2. **Root**: The root is the topmost node of a tree. It serves as the starting point for traversing the tree and accessing its elements. - -3. **Parent and Child**: Nodes in a tree are connected in a parent-child relationship. A parent node is the immediate predecessor of its child node, and a child node is a direct descendant of its parent node. - -4. **Leaf**: A leaf node is a node that does not have any child nodes. It is located at the bottom of the tree. - -5. **Binary Tree**: A binary tree is a tree in which each node can have at most two child nodes, the left child and the right child. Binary trees are commonly used in search algorithms and binary tree traversals. - -6. **Binary Search Tree (BST)**: A binary search tree is a binary tree in which the left child of a node contains a value less than the node's value, and the right child contains a value greater than the node's value. BSTs are efficient for searching, insertion, and deletion operations. - -7. **Traversal**: Traversal refers to the process of visiting all the nodes in a tree in a specific order. Common traversal algorithms include in-order, pre-order, and post-order traversals. In-order traversal visits the left subtree, then the root, and finally the right subtree. Pre-order traversal visits the root, then the left subtree, and finally the right subtree. Post-order traversal visits the left subtree, then the right subtree, and finally the root. - -8. **Balanced Trees**: Balanced trees are trees that maintain a balance between the left and right subtrees of each node. Examples of balanced trees include AVL trees and red-black trees. Balanced trees provide faster search, insertion, and deletion operations compared to regular binary search trees. - -9. **B-Tree**: A B-tree is a self-balancing search tree that can have more than two children per node. It is commonly used in file systems and databases, as it provides efficient disk access and supports large amounts of data. - -These are just some of the key concepts related to DSA trees. Trees are a rich topic with many variations and algorithms associated with them. It's important to understand these concepts and their implementations in different programming languages to effectively use trees in your programs. - - -## Types of Trees - -![alt text](image.png) - -1. **Binary Tree**: A binary tree is a tree in which each node can have at most two child nodes, referred to as the left child and the right child. Binary trees are commonly used in search algorithms and binary tree traversals. - -2. **Binary Search Tree (BST)**: A binary search tree is a binary tree in which the left child of a node contains a value less than the node's value, and the right child contains a value greater than the node's value. BSTs are efficient for searching, insertion, and deletion operations. - -3. **AVL Tree**: An AVL tree is a self-balancing binary search tree. It ensures that the heights of the left and right subtrees of any node differ by at most one. AVL trees provide faster search, insertion, and deletion operations compared to regular binary search trees. - -4. **Red-Black Tree**: A red-black tree is another self-balancing binary search tree. It maintains balance by coloring the nodes red or black and applying specific rules during insertion and deletion operations. Red-black trees guarantee logarithmic time complexity for search, insertion, and deletion. - -5. **B-Tree**: A B-tree is a self-balancing search tree that can have more than two children per node. It is commonly used in file systems and databases, as it provides efficient disk access and supports large amounts of data. - -## Basic Operations on Trees - -1. **Insertion**: Adding a new node to the tree at the appropriate position based on its value. - -2. **Deletion**: Removing a node from the tree while maintaining the tree's structure and properties. - -3. **Search**: Finding a specific value or node in the tree. - -4. **Traversal**: Visiting all the nodes in the tree in a specific order. Common traversal algorithms include in-order, pre-order, and post-order traversals. - -## Implementation in Different Languages - -Trees can be implemented in various programming languages. Here are some examples: - -- **Java**: Java provides built-in classes like `TreeNode` and `BinarySearchTree` to implement trees. You can also create custom classes and use recursion for tree operations. - -- **Python**: Python offers flexibility in implementing trees using classes and objects. You can define a `TreeNode` class and implement tree operations using methods and recursion. - -- **C++**: C++ allows you to create tree structures using classes and pointers. You can define a `TreeNode` class and implement tree operations using pointers and recursive functions. - -- **JavaScript**: JavaScript provides the flexibility of implementing trees using objects and classes. You can define a `TreeNode` object and implement tree operations using object-oriented programming concepts. - -Remember to refer to the specific documentation and resources for each programming language to understand the syntax and details of implementing trees. - -## Implementation in Different Languages - -Trees can be implemented in various programming languages. Here are some examples: - -- **Java**: - -```java -class TreeNode { - int data; - TreeNode left; - TreeNode right; - - public TreeNode(int data) { - this.data = data; - this.left = null; - this.right = null; - } -} - -class BinaryTree { - TreeNode root; - - public BinaryTree(int data) { - this.root = new TreeNode(data); - } - - public void insert(int data) { - // Implementation of insertion - } - - public void delete(int data) { - // Implementation of deletion - } - - public TreeNode search(int data) { - // Implementation of search - return null; - } - - public void inOrderTraversal(TreeNode node) { - // Implementation of in-order traversal - } -} - -public class Main { - public static void main(String[] args) { - BinaryTree tree = new BinaryTree(5); - tree.insert(3); - tree.insert(7); - tree.insert(2); - tree.insert(4); - tree.insert(6); - tree.insert(8); - - tree.inOrderTraversal(tree.root); - } -} -``` - -Output: -``` -2 3 4 5 6 7 8 -``` - -- **Python**: - -```python -class TreeNode: - def __init__(self, data): - self.data = data - self.left = None - self.right = None - -class BinaryTree: - def __init__(self, data): - self.root = TreeNode(data) - - def insert(self, data): - # Implementation of insertion - - def delete(self, data): - # Implementation of deletion - - def search(self, data): - # Implementation of search - return None - - def in_order_traversal(self, node): - # Implementation of in-order traversal - -tree = BinaryTree(5) -tree.insert(3) -tree.insert(7) -tree.insert(2) -tree.insert(4) -tree.insert(6) -tree.insert(8) - -tree.in_order_traversal(tree.root) -``` - -Output: -``` -2 3 4 5 6 7 8 -``` - -- **C++**: - -```cpp -class TreeNode { -public: - int data; - TreeNode* left; - TreeNode* right; - - TreeNode(int data) { - this->data = data; - this->left = nullptr; - this->right = nullptr; - } -}; - -class BinaryTree { -public: - TreeNode* root; - - BinaryTree(int data) { - this->root = new TreeNode(data); - } - - void insert(int data) { - // Implementation of insertion - } - - void deleteNode(int data) { - // Implementation of deletion - } - - TreeNode* search(int data) { - // Implementation of search - return nullptr; - } - - void inOrderTraversal(TreeNode* node) { - // Implementation of in-order traversal - } -}; - -int main() { - BinaryTree tree(5); - tree.insert(3); - tree.insert(7); - tree.insert(2); - tree.insert(4); - tree.insert(6); - tree.insert(8); - - tree.inOrderTraversal(tree.root); - - return 0; -} -``` - -Output: -``` -2 3 4 5 6 7 8 -``` - -- **JavaScript**: - -```javascript -class TreeNode { - constructor(data) { - this.data = data; - this.left = null; - this.right = null; - } -} - -class BinaryTree { - constructor(data) { - this.root = new TreeNode(data); - } - - insert(data) { - // Implementation of insertion - } - - delete(data) { - // Implementation of deletion - } - - search(data) { - // Implementation of search - return null; - } - - inOrderTraversal(node) { - // Implementation of in-order traversal - } -} - -const tree = new BinaryTree(5); -tree.insert(3); -tree.insert(7); -tree.insert(2); -tree.insert(4); -tree.insert(6); -tree.insert(8); - -tree.inOrderTraversal(tree.root); -``` - -Output: -``` -2 3 4 5 6 7 8 -``` - -Remember to refer to the specific documentation and resources for each programming language to understand the syntax and details of implementing trees. - - -## Operations on Trees in Python - -Here are some examples of tree operations implemented in Python: - -1. **Insertion**: - -```python -class TreeNode: - def __init__(self, data): - self.data = data - self.left = None - self.right = None - -class BinaryTree: - def __init__(self, data): - self.root = TreeNode(data) - - def insert(self, data): - if self.root is None: - self.root = TreeNode(data) - else: - self._insert_recursive(self.root, data) - - def _insert_recursive(self, node, data): - if data < node.data: - if node.left is None: - node.left = TreeNode(data) - else: - self._insert_recursive(node.left, data) - else: - if node.right is None: - node.right = TreeNode(data) - else: - self._insert_recursive(node.right, data) -``` - -2. **Deletion**: - -```python -class BinaryTree: - # ... - - def delete(self, data): - self.root = self._delete_recursive(self.root, data) - - def _delete_recursive(self, node, data): - if node is None: - return node - - if data < node.data: - node.left = self._delete_recursive(node.left, data) - elif data > node.data: - node.right = self._delete_recursive(node.right, data) - else: - if node.left is None: - return node.right - elif node.right is None: - return node.left - else: - min_node = self._find_min(node.right) - node.data = min_node.data - node.right = self._delete_recursive(node.right, min_node.data) - - return node - - def _find_min(self, node): - current = node - while current.left is not None: - current = current.left - return current -``` - -3. **Search**: - -```python -class BinaryTree: - # ... - - def search(self, data): - return self._search_recursive(self.root, data) - - def _search_recursive(self, node, data): - if node is None or node.data == data: - return node - - if data < node.data: - return self._search_recursive(node.left, data) - else: - return self._search_recursive(node.right, data) -``` - -4. **Traversal**: - -```python -class BinaryTree: - # ... - - def in_order_traversal(self, node): - if node is not None: - self.in_order_traversal(node.left) - print(node.data, end=" ") - self.in_order_traversal(node.right) -``` - -Example usage: - -```python -tree = BinaryTree(5) -tree.insert(3) -tree.insert(7) -tree.insert(2) -tree.insert(4) -tree.insert(6) -tree.insert(8) - -tree.in_order_traversal(tree.root) -``` - -Output: -``` -2 3 4 5 6 7 8 -``` - -Remember to refer to the specific documentation and resources for Python to understand the syntax and details of implementing trees. - -Practise more and more ........... - diff --git a/docs/dsa/Trees/_category_.json b/docs/dsa/Trees/_category_.json deleted file mode 100644 index 90071153a..000000000 --- a/docs/dsa/Trees/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Trees", - "position": 13, - "link": { - "type": "generated-index", - "description": "In data structures and algorithms (DSA), a tree is a hierarchical data structure consisting of nodes connected by edges. It is a nonlinear data structure that represents a set of elements in a hierarchical manner, with one node being designated as the root and the remaining nodes forming subtrees." - } -} diff --git a/docs/dsa/Trees/image-1.png b/docs/dsa/Trees/image-1.png deleted file mode 100644 index b7e53cda5..000000000 Binary files a/docs/dsa/Trees/image-1.png and /dev/null differ diff --git a/docs/dsa/Trees/image.png b/docs/dsa/Trees/image.png deleted file mode 100644 index cb119966c..000000000 Binary files a/docs/dsa/Trees/image.png and /dev/null differ diff --git a/docs/dsa/_category_.json b/docs/dsa/_category_.json deleted file mode 100644 index 4bf18bdf8..000000000 --- a/docs/dsa/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "DSA", - "position": 8, - "link": { - "type": "generated-index", - "description": "Data Structures and Algorithms are the building blocks of computer science. This section will help you to prepare for your interviews and competitive programming." - } - } \ No newline at end of file diff --git a/docs/dsa/algorithms/Greedy.md b/docs/dsa/algorithms/Greedy.md deleted file mode 100644 index 7baf470ff..000000000 --- a/docs/dsa/algorithms/Greedy.md +++ /dev/null @@ -1,261 +0,0 @@ ---- -id: greedy-in-dsa -title: Greedy Algorithm in Data Structures and Algorithms -sidebar_label: Greedy Algorithm -sidebar_position: 6 -description: "" -tags: - [dsa,data-algorithms , Greedy - ] ---- - -The Greedy algorithm is a simple and intuitive approach used to solve optimization problems. It follows the greedy principle of making locally optimal choices at each step to find a global optimum solution. -![alt text](image-6.png) - -To implement a Greedy algorithm, follow these steps: - -1. Understand the problem: Identify the objective or goal you want to achieve. - -2. Define the problem as subproblems: Break down the problem into smaller, independent subproblems. - -3. Determine the greedy choice: Make a locally optimal choice at each step that leads to the overall optimal solution. - -4. Verify feasibility: Check if the chosen option satisfies constraints and requirements. - -5. Update the solution: Include the chosen option in the current solution. - -6. Repeat steps 3-5: Continue making greedy choices until the problem is solved or the desired solution is obtained. - - -### Types of Greedy Algorithms - -1. Activity Selection: This algorithm selects a maximum number of compatible activities that can be performed in a given time frame. It prioritizes activities based on their finish times or other criteria. - -2. Fractional Knapsack: This algorithm solves the fractional knapsack problem, where items can be divided into fractions. It selects items based on their value-to-weight ratio, maximizing the total value while considering the capacity constraint. - -3. Huffman Coding: This algorithm is used for data compression. It assigns variable-length codes to characters based on their frequency of occurrence, with more frequent characters having shorter codes. - -4. Dijkstra's Algorithm: This algorithm finds the shortest path in a weighted graph from a source vertex to all other vertices. It selects the vertex with the minimum distance at each step, gradually expanding the shortest path tree. - -5. Prim's Algorithm: This algorithm finds the minimum spanning tree of a connected weighted graph. It starts with an arbitrary vertex and greedily adds the edge with the minimum weight that connects the current tree to a new vertex. - -6. Kruskal's Algorithm: This algorithm also finds the minimum spanning tree of a connected weighted graph. It sorts the edges in non-decreasing order of their weights and greedily adds the edges that do not form a cycle. - -7. Coin Change: This algorithm solves the problem of making change for a given amount using the fewest number of coins. It selects the largest denomination coins first until the desired amount is reached. - -8. Interval Scheduling: This algorithm schedules a maximum number of tasks with overlapping intervals. It selects tasks based on their finish times or other criteria, maximizing the number of non-overlapping tasks. - -These are just a few examples of greedy algorithms. Each algorithm has its own specific problem-solving approach, but they all share the common characteristic of making locally optimal choices at each step to achieve a global optimum solution. - - -### Advantages of the Greedy algorithm: - -- Simplicity: Easy to understand and implement compared to complex algorithms. -- Efficiency: Provides fast and efficient solutions in many cases. -- Intuitive: Follows a natural and intuitive thought process. - -### Disadvantages of the Greedy algorithm: - -- Lack of global optimization: Locally optimal choices may not always lead to the globally optimal solution. -- Suboptimal choices: Locally optimal choices may not result in the best overall solution. -- Limited applicability: Not suitable for all problems, especially those requiring a comprehensive approach. - -Note that the Greedy algorithm may not always be the best choice. Analyze the problem and consider other approaches for the most efficient solution. - -**Here's an example code using the Greedy algorithm:** -#### Codes in Different Languages - - - -```Python showLineNumbers -def knapsack_greedy(values, weights, capacity): - # Create a list of items with their values and weights - items = list(zip(values, weights)) - - # Sort the items based on their value-to-weight ratio in descending order - items.sort(key=lambda x: x[0] / x[1], reverse=True) - - # Initialize the total value and total weight - total_value = 0 - total_weight = 0 - - # Iterate through the sorted items - for value, weight in items: - # Check if adding the current item exceeds the capacity - if total_weight + weight <= capacity: - # Add the item to the knapsack - total_value += value - total_weight += weight - - return total_value - -# Example usage -values = [60, 100, 120] -weights = [10, 20, 30] -capacity = 50 - -max_value = knapsack_greedy(values, weights, capacity) -print("Maximum value:", max_value) - -``` - - - ```cpp - #include -#include -#include -using namespace std; - -struct Item { - int value; - int weight; -}; - -bool compare(Item a, Item b) { - double r1 = (double)a.value / a.weight; - double r2 = (double)b.value / b.weight; - return r1 > r2; -} - -int knapsack_greedy(vector& values, vector& weights, int capacity) { - vector items(values.size()); - for (size_t i = 0; i < values.size(); ++i) { - items[i] = {values[i], weights[i]}; - } - - sort(items.begin(), items.end(), compare); - - int total_value = 0; - int total_weight = 0; - - for (auto& item : items) { - if (total_weight + item.weight <= capacity) { - total_value += item.value; - total_weight += item.weight; - } - } - - return total_value; -} - -int main() { - vector values = {60, 100, 120}; - vector weights = {10, 20, 30}; - int capacity = 50; - - int max_value = knapsack_greedy(values, weights, capacity); - cout << "Maximum value: " << max_value << endl; - - return 0; -} - - ``` - - -``` jsx showLineNumbers -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -class Item { - int value; - int weight; - - Item(int value, int weight) { - this.value = value; - this.weight = weight; - } -} - -public class KnapsackGreedy { - - public static int knapsackGreedy(int[] values, int[] weights, int capacity) { - List items = new ArrayList<>(); - for (int i = 0; i < values.length; i++) { - items.add(new Item(values[i], weights[i])); - } - - Collections.sort(items, new Comparator() { - public int compare(Item a, Item b) { - double r1 = (double) a.value / a.weight; - double r2 = (double) b.value / b.weight; - return Double.compare(r2, r1); - } - }); - - int totalValue = 0; - int totalWeight = 0; - - for (Item item : items) { - if (totalWeight + item.weight <= capacity) { - totalValue += item.value; - totalWeight += item.weight; - } - } - - return totalValue; - } - - public static void main(String[] args) { - int[] values = {60, 100, 120}; - int[] weights = {10, 20, 30}; - int capacity = 50; - - int maxValue = knapsackGreedy(values, weights, capacity); - System.out.println("Maximum value: " + maxValue); - } -} - -``` - - - -``` jsx showLineNumbers -function knapsackGreedy(values, weights, capacity) { - let items = []; - for (let i = 0; i < values.length; i++) { - items.push({ value: values[i], weight: weights[i] }); - } - - items.sort((a, b) => (b.value / b.weight) - (a.value / a.weight)); - - let totalValue = 0; - let totalWeight = 0; - - for (let item of items) { - if (totalWeight + item.weight <= capacity) { - totalValue += item.value; - totalWeight += item.weight; - } - } - - return totalValue; -} - -// Example usage -let values = [60, 100, 120]; -let weights = [10, 20, 30]; -let capacity = 50; - -let maxValue = knapsackGreedy(values, weights, capacity); -console.log("Maximum value:", maxValue); - - -``` - - - - - -This code demonstrates the Greedy algorithm in action by solving the Knapsack problem. The goal is to maximize the total value of items that can be put into a knapsack with a given capacity. The algorithm selects items based on their value-to-weight ratio, choosing the most valuable items first until the knapsack is full. - -### Conclusion - -The Greedy algorithm is a powerful and intuitive approach for solving optimization problems. It follows the principle of making locally optimal choices at each step to find a global optimum solution. - -The advantages of the Greedy algorithm include its simplicity, efficiency, and intuitive thought process. It is easy to understand and implement compared to complex algorithms, provides fast and efficient solutions in many cases, and follows a natural thought process. - -However, the Greedy algorithm also has its limitations. Locally optimal choices may not always lead to the globally optimal solution, resulting in suboptimal choices. It is not suitable for all problems, especially those requiring a comprehensive approach. - -In conclusion, the Greedy algorithm is a valuable tool in solving optimization problems, but it is important to analyze the problem and consider other approaches for the most efficient solution. \ No newline at end of file diff --git a/docs/dsa/algorithms/_category_.json b/docs/dsa/algorithms/_category_.json deleted file mode 100644 index 3055c678d..000000000 --- a/docs/dsa/algorithms/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Algorithms", - "position": 14, - "link": { - "type": "generated-index", - "description": "Searching algorithms are a set of techniques used to find a specific element or value in a collection of data. They are commonly used in computer science and data analysis to efficiently locate desired information." - } - } \ No newline at end of file diff --git a/docs/dsa/algorithms/backtracking.md b/docs/dsa/algorithms/backtracking.md deleted file mode 100644 index 9d15acdfd..000000000 --- a/docs/dsa/algorithms/backtracking.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -id: backtracking-in-dsa -title: Backtracking in Data Structures and Algorithms -sidebar_label: Backtracking Algorithm -sidebar_position: 1 -description: "Backtracking is a technique used to solve problems by exploring all possible solutions." -tags : [dsa,data-algorithms , backtracking] ---- - - -## Backtracking in Python - -Backtracking is a technique used to solve problems by exploring all possible solutions. It is especially useful when the problem can be broken down into a series of decisions or choices. -![alt text](image-3.png) - -To implement backtracking in Python, you can follow these steps: - -1. Define a function that takes the problem and a partial solution as input. -2. Check if the solution is complete. If it is, return the solution. -3. Generate possible candidates for the next step. -4. Iterate through the candidates. -5. Make a choice and update the solution. -6. Recursively call the function with the updated solution. -7. If a valid solution is found, return it. -8. Undo the choice and continue with the next candidate. -9. If no valid solution is found, return None. - -Here's an example implementation of the backtracking algorithm in Python: - -```python -def backtrack(problem, solution): - # Base case: if the solution is complete, return it - if is_solution(problem, solution): - return solution - - # Generate possible candidates for the next step - candidates = generate_candidates(problem, solution) - - # Iterate through the candidates - for candidate in candidates: - # Make a choice and update the solution - make_choice(problem, solution, candidate) - - # Recursively backtrack with the updated solution - result = backtrack(problem, solution) - - # If a valid solution is found, return it - if result is not None: - return result - - # Undo the choice and continue with the next candidate - undo_choice(problem, solution, candidate) - - # If no valid solution is found, return None - return None -``` - -You can customize the `is_solution`, `generate_candidates`, `make_choice`, and `undo_choice` functions to fit your specific problem. - -Remember, backtracking explores all possible solutions, so it can be computationally expensive for large problem spaces. However, it is a powerful technique for solving problems that can be represented as a series of choices or decisions. - - -### Example: Permutations of Letters - -The task is to find all possible arrangements (permutations) of a given set of letters. - -### Explanation: - -**Function Definition:** - -We define a function permute(letters, current_perm, all_permutations). -letters is the original set of letters. -current_perm is a list to hold the current permutation being built. -all_permutations is a list to store all the final permutations. -Base Case: - -If all letters have been used (i.e., len(current_perm) == len(letters)), we've found a complete permutation. -Append the current_perm to the all_permutations list. -Recursive Exploration: - -Iterate through the remaining letters in letters. -For each letter: -Add the letter to the current_perm. -Make a recursive call to permute with the updated current_perm and the remaining letters (excluding the chosen letter). -After the recursive call (exploring possibilities with the chosen letter), remove the letter from current_perm to backtrack and explore other options (avoiding duplicates). -#### Codes in Different Languages - - - - - - ```cpp -#include -#include -using namespace std; -void permute(vector& letters, vector& current_perm, vector>& all_permutations) { - if (current_perm.size() == letters.size()) { - all_permutations.push_back(current_perm); - return; - } - - for (size_t i = 0; i < letters.size(); ++i) { - if (find(current_perm.begin(), current_perm.end(), letters[i]) == current_perm.end()) { - current_perm.push_back(letters[i]); - permute(letters, current_perm, all_permutations); - current_perm.pop_back(); - } - } -} - -int main() { - vector letters = {'a', 'b', 'c'}; - vector current_perm; - vector> all_permutations; - - permute(letters, current_perm, all_permutations); - - cout << "All permutations:\n"; - for (const auto& perm : all_permutations) { - for (char c : perm) { - cout << c << ' '; - } - cout << '\n'; - } - - return 0; -} - - ``` - - -```Python showLineNumbers -def permute(letters, current_perm=[], all_permutations=[]): - """Finds all permutations (arrangements) of the given letters.""" - if len(current_perm) == len(letters): - all_permutations.append(current_perm.copy()) # Append a copy to avoid modification - return - - for i in range(len(letters)): - if letters[i] not in current_perm: # Avoid duplicates - current_perm.append(letters[i]) - permute(letters, current_perm, all_permutations) - current_perm.pop() # Backtrack - -# Example usage -letters = ['a', 'b', 'c'] -permute(letters, all_permutations=[]) -print("All permutations:", all_permutations) - - -``` - - -``` jsx showLineNumbers -import java.util.ArrayList; -import java.util.List; - -public class Permutations { - public static void permute(char[] letters, List currentPerm, List> allPermutations) { - if (currentPerm.size() == letters.length) { - allPermutations.add(new ArrayList<>(currentPerm)); - return; - } - - for (char letter : letters) { - if (!currentPerm.contains(letter)) { - currentPerm.add(letter); - permute(letters, currentPerm, allPermutations); - currentPerm.remove(currentPerm.size() - 1); - } - } - } - - public static void main(String[] args) { - char[] letters = {'a', 'b', 'c'}; - List currentPerm = new ArrayList<>(); - List> allPermutations = new ArrayList<>(); - - permute(letters, currentPerm, allPermutations); - - System.out.println("All permutations:"); - for (List perm : allPermutations) { - for (char c : perm) { - System.out.print(c + " "); - } - System.out.println(); - } - } -} - - -``` - - - -``` jsx showLineNumbers -function permute(letters, currentPerm = [], allPermutations = []) { - if (currentPerm.length === letters.length) { - allPermutations.push([...currentPerm]); // Append a copy - return; - } - - for (let i = 0; i < letters.length; i++) { - if (!currentPerm.includes(letters[i])) { - currentPerm.push(letters[i]); - permute(letters, currentPerm, allPermutations); - currentPerm.pop(); // Backtrack - } - } -} - -// Example usage -let letters = ['a', 'b', 'c']; -let allPermutations = []; -permute(letters, [], allPermutations); -console.log("All permutations:", allPermutations); - - -``` - - - - \ No newline at end of file diff --git a/docs/dsa/algorithms/bitwise.md b/docs/dsa/algorithms/bitwise.md deleted file mode 100644 index f1b6884d9..000000000 --- a/docs/dsa/algorithms/bitwise.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -id: bitwise-in-dsa -title: Bitwise Algorithm in Data Structures and Algorithms -sidebar_label: Bitwise Algorithm -sidebar_position: 1 -description: "" -tags: - [dsa,data-algorithms , bitwise - ] ---- - -Bitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits within an integer's binary representation to solve problems efficiently. These algorithms use bitwise operators like AND, OR, XOR, NOT, LEFT SHIFT, and RIGHT SHIFT. They are fundamental in low-level programming, encryption, compression, and optimization tasks due to their direct manipulation of data at the bit level. -![bitwise](image-7.png) - -### Explanation -Bitwise algorithms operate directly on the binary representation of numbers. For example, the bitwise AND operator (&) compares each bit of two numbers and returns a new number whose bits are set to 1 only if both compared bits are 1. Other operators work similarly, manipulating bits to achieve various outcomes. - -## Advantages -- Efficiency: Bitwise operations are extremely fast, as they are directly supported by the processor. -- Low-level control: They provide granular control over data, allowing for optimizations not possible with higher-level abstractions. -- Space-saving: Bitwise operations can be used to compactly store and manipulate data, reducing memory usage. - -## Disadvantages -- Readability: Code using bitwise operations can be hard to read and understand, especially for those not familiar with these operations. -- Error-prone: Small mistakes in bitwise operations can lead to significant bugs, as the operations are very low-level. -- Limited applicability: Not all problems benefit from bitwise optimizations; their use is somewhat niche. - -## Application in a Problem -Consider the problem of finding the unique number in an array where all numbers except one are repeated twice. A bitwise XOR operation can solve this efficiently. - -**Example** -Given an array: [4, 1, 2, 1, 2], find the unique number. - -## Step-by-step: - -- XOR all the numbers in the array. -- Repeated numbers will cancel each other out because n XOR n = 0. -- The result will be the unique number, as n XOR 0 = n. - -## Implementation: -```python -def findUnique(arr): - unique = 0 - for num in arr: - unique ^= num - return unique - -arr = [4, 1, 2, 1, 2] -print(findUnique(arr)) # Output: 4 -``` - -In this example, the XOR operation is used to find the unique number efficiently. This showcases the power of bitwise operations in solving specific types of problems with minimal code and high performance. - - -Bitwise algorithms leverage the fundamental operations of bitwise logic to perform calculations directly on the binary representations of numbers. This approach offers a unique blend of efficiency, precision, and low-level data manipulation capabilities that are unmatched by higher-level algorithmic strategies. While they excel in specific domains such as cryptography, data compression, and systems programming, their utility is somewhat specialized, and they require a good understanding of binary arithmetic to be used effectively. \ No newline at end of file diff --git a/docs/dsa/algorithms/image-1.png b/docs/dsa/algorithms/image-1.png deleted file mode 100644 index 90eb9cb30..000000000 Binary files a/docs/dsa/algorithms/image-1.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-10.png b/docs/dsa/algorithms/image-10.png deleted file mode 100644 index 8b3c8d715..000000000 Binary files a/docs/dsa/algorithms/image-10.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-2.png b/docs/dsa/algorithms/image-2.png deleted file mode 100644 index e9a423c7d..000000000 Binary files a/docs/dsa/algorithms/image-2.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-3.png b/docs/dsa/algorithms/image-3.png deleted file mode 100644 index 6156021b3..000000000 Binary files a/docs/dsa/algorithms/image-3.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-4.png b/docs/dsa/algorithms/image-4.png deleted file mode 100644 index 3d88cf9c3..000000000 Binary files a/docs/dsa/algorithms/image-4.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-5.png b/docs/dsa/algorithms/image-5.png deleted file mode 100644 index f5a193ae5..000000000 Binary files a/docs/dsa/algorithms/image-5.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-6.png b/docs/dsa/algorithms/image-6.png deleted file mode 100644 index 51477bf45..000000000 Binary files a/docs/dsa/algorithms/image-6.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-7.png b/docs/dsa/algorithms/image-7.png deleted file mode 100644 index a0ecb3041..000000000 Binary files a/docs/dsa/algorithms/image-7.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-8.png b/docs/dsa/algorithms/image-8.png deleted file mode 100644 index 7c3d3ec68..000000000 Binary files a/docs/dsa/algorithms/image-8.png and /dev/null differ diff --git a/docs/dsa/algorithms/image-9.png b/docs/dsa/algorithms/image-9.png deleted file mode 100644 index 61b41ab1a..000000000 Binary files a/docs/dsa/algorithms/image-9.png and /dev/null differ diff --git a/docs/dsa/algorithms/image.png b/docs/dsa/algorithms/image.png deleted file mode 100644 index 0c79cbbf2..000000000 Binary files a/docs/dsa/algorithms/image.png and /dev/null differ diff --git a/docs/dsa/algorithms/mathematical_algorithm.md b/docs/dsa/algorithms/mathematical_algorithm.md deleted file mode 100644 index 6d8c718e8..000000000 --- a/docs/dsa/algorithms/mathematical_algorithm.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -id: mathematicalAlgorithm-in-dsa -title: Mathematical Algorithm in Data Structures and Algorithms -sidebar_label: Mathematical Algorithm -sidebar_position: 9 -description: "Learn about mathematical algorithms and how they can be applied in data structures and algorithms. Understand the importance of choosing the right algorithm and implementing it correctly for efficient problem-solving." -tags: [dsa, data-algorithms, mathematical-algorithm] ---- - -A mathematical algorithm is a step-by-step procedure or set of rules used to solve a mathematical problem or perform a mathematical computation. It provides a systematic approach to efficiently and accurately solve complex mathematical problems. - - -![mathematics-algorithm](image-9.png) - -Mathematical algorithms find applications in various areas, including data structures and algorithms, cryptography, optimization problems, and numerical analysis. They offer a structured way to solve problems and can be implemented in programming languages like JavaScript. - - -To apply a mathematical algorithm, it is crucial to understand the problem and select the appropriate algorithm. Let's consider an example: - -Suppose you have a list of numbers and you want to find their sum. You can use the "sum algorithm" to solve this problem. Here's how it works: - -1. Initialize a variable called sum to 0. -2. Iterate through each number in the list. -3. Add the current number to the sum variable. -4. Repeat steps 2 and 3 until all numbers in the list are processed. -5. The final value of sum will be the sum of all the numbers in the list. - -### Example -Here's an example implementation of the sum algorithm in JavaScript: - -```python -def sum_algorithm(numbers): - sum = 0 - for num in numbers: - sum += num - return sum -``` - -By applying the sum algorithm, you can easily calculate the sum of any list of numbers. This is just one example of how mathematical algorithms can be applied to solve problems. Depending on the problem, different algorithms may be required. - -Remember to understand the problem, choose the appropriate algorithm, and implement it correctly to obtain the desired result. - - -This example highlights the application of mathematical algorithms to solve problems. In this case, the sum algorithm provides a straightforward way to calculate the sum of a list of numbers. However, it's important to note that different problems may require different algorithms. - -To effectively solve problems using algorithms, it is crucial to understand the problem at hand, choose the appropriate algorithm, and implement it correctly. By following these steps, you can obtain the desired result and efficiently solve a wide range of problems. \ No newline at end of file diff --git a/docs/dsa/algorithms/patternsearchalgorithm.md b/docs/dsa/algorithms/patternsearchalgorithm.md deleted file mode 100644 index f371a50e5..000000000 --- a/docs/dsa/algorithms/patternsearchalgorithm.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -id: patternsearching-in-dsa -title: Pattern Searching Algorithm in Data Structures and Algorithms -sidebar_label: Pattern Searching Algorithm -sidebar_position: 7 -description: "The Pattern Searching Algorithm is a powerful tool used to find occurrences of a pattern within a larger text or string." -tags: [dsa,data-algorithms , pattern-searching] ---- - - -The Pattern Searching Algorithm is a powerful tool used to find occurrences of a pattern within a larger text or string. It is commonly employed in string matching problems, where the goal is to search for a specific pattern or substring within a given text. - -![pattern search](image-8.png) - -This algorithm compares the pattern with each possible substring of the text, starting from the leftmost position. When a match is found, the algorithm reports the index or position of the match. There are several variations of the Pattern Searching Algorithm, including the Naive Pattern Searching Algorithm, Knuth-Morris-Pratt (KMP) Algorithm, Rabin-Karp Algorithm, and Boyer-Moore Algorithm, each with its own advantages and disadvantages. - -### Advantages of the Pattern Searching Algorithm: - -1. Versatility: The algorithm can be applied to various string matching problems, making it a valuable tool in many applications. -2. Flexibility: Different variations of the algorithm allow for different trade-offs in terms of time complexity, space complexity, and implementation complexity. -3. Efficiency: Depending on the specific variation used, the Pattern Searching Algorithm can achieve efficient search times, particularly in large texts. - -### Disadvantages of the Pattern Searching Algorithm: - -1. Complexity: Some variations of the algorithm can be complex to understand and implement, especially for beginners. -2. Performance: The performance of the algorithm can vary depending on the specific variation used and the characteristics of the input text and pattern. In some cases, the algorithm may not be the most efficient solution. - -Here's an example code problem to illustrate the usage of the Pattern Searching Algorithm: - -#### Codes in Different Languages - - - -```Python showLineNumbers -def pattern_search(text, pattern): - result = [] - text_length = len(text) - pattern_length = len(pattern) - - for i in range(text_length - pattern_length + 1): - j = 0 - while j < pattern_length: - if text[i + j] != pattern[j]: - break - j += 1 - if j == pattern_length: - result.append(i) - - return result - -text = "ABABDABACDABABCABAB" -pattern = "ABABC" -matches = pattern_search(text, pattern) -print("Pattern found at positions:", matches) - -``` - - - ```cpp - #include -#include -#include -#include -using namespace std; -vector pattern_search(const string &text, const string &pattern) { - vector result; - int text_length = text.length(); - int pattern_length = pattern.length(); - - for (int i = 0; i <= text_length - pattern_length; i++) { - int j = 0; - while (j < pattern_length && text[i + j] == pattern[j]) { - j++; - } - if (j == pattern_length) { - result.push_back(i); - } - } - - return result; -} - -int main() { - string text = "ABABDABACDABABCABAB"; - string pattern = "ABABC"; - vector matches = pattern_search(text, pattern); - - cout << "Pattern found at positions: "; - for (int position : matches) { - cout << position << " "; - } - cout << endl; - - return 0; -} - - - ``` - - -``` jsx showLineNumbers -import java.util.ArrayList; -import java.util.List; - -public class PatternSearch { - public static List patternSearch(String text, String pattern) { - List result = new ArrayList<>(); - int textLength = text.length(); - int patternLength = pattern.length(); - - for (int i = 0; i <= textLength - patternLength; i++) { - int j = 0; - while (j < patternLength && text.charAt(i + j) == pattern.charAt(j)) { - j++; - } - if (j == patternLength) { - result.add(i); - } - } - - return result; - } - - public static void main(String[] args) { - String text = "ABABDABACDABABCABAB"; - String pattern = "ABABC"; - List matches = patternSearch(text, pattern); - - System.out.print("Pattern found at positions: "); - for (int position : matches) { - System.out.print(position + " "); - } - System.out.println(); - } -} - - -``` - - - -``` jsx showLineNumbers -function patternSearch(text, pattern) { - let result = []; - let textLength = text.length; - let patternLength = pattern.length; - - for (let i = 0; i <= textLength - patternLength; i++) { - let j = 0; - while (j < patternLength && text[i + j] === pattern[j]) { - j++; - } - if (j === patternLength) { - result.push(i); - } - } - - return result; -} - -let text = "ABABDABACDABABCABAB"; -let pattern = "ABABC"; -let matches = patternSearch(text, pattern); -console.log("Pattern found at positions:", matches); - - - -``` - - - - - -In this example, we have a text string "ABABDABACDABABCABAB" and we want to search for the pattern "ABABC" within it. The `patternSearch` function implements the Naive Pattern Searching Algorithm. It iterates through the text, comparing each substring of the same length as the pattern with the pattern itself. If a match is found, the starting position of the match is added to the result array. Finally, the function returns the array of positions where the pattern was found. - -When we run this code, it will output: "Pattern found at positions: [0, 10]". This means that the pattern "ABABC" was found at positions 0 and 10 within the text string. - - -The pattern search algorithm, also known as the Naive Pattern Searching Algorithm, is a simple and straightforward approach to finding occurrences of a pattern within a text string. It works by iterating through the text and comparing each substring of the same length as the pattern with the pattern itself. - -The algorithm starts by initializing an empty array to store the positions where the pattern is found. Then, it iterates through the text string, comparing each substring of the same length as the pattern with the pattern itself. If a match is found, the starting position of the match is added to the result array. - -Once the algorithm has finished iterating through the entire text, it returns the array of positions where the pattern was found. This allows us to determine the locations of all occurrences of the pattern within the text. - -The Naive Pattern Searching Algorithm is relatively simple to implement and understand, making it a good starting point for pattern searching tasks. However, it has a time complexity of O((n-m+1)*m), where n is the length of the text and m is the length of the pattern. This means that the algorithm's performance can degrade for large texts or patterns. - -There are more advanced pattern searching algorithms, such as the Knuth-Morris-Pratt (KMP) algorithm and the Boyer-Moore algorithm, which offer better time complexity and improved performance in certain scenarios. However, the Naive Pattern Searching Algorithm serves as a foundation for understanding pattern searching concepts and can be a useful starting point for simple cases. diff --git a/docs/dsa/algorithms/searching_algorithm.md b/docs/dsa/algorithms/searching_algorithm.md deleted file mode 100644 index a26f654e6..000000000 --- a/docs/dsa/algorithms/searching_algorithm.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -id: searching-in-dsa -title: Searching in Data Structures and Algorithms -sidebar_label: Searching Algorithm -sidebar_position: 1 -description: "" -tags: [dsa, data-algorithms, searching] ---- - -Searching is a fundamental operation in computer science and is widely used in various applications. In the context of Data Structures and Algorithms (DSA), searching refers to the process of finding a specific element within a collection of data. - -![alt text](image.png) - -## Linear Search - -Linear search is a simple algorithm that sequentially checks each element in a collection until the target element is found or the end of the collection is reached. It is commonly used for small collections or unsorted data. - - - -
- -```python -def linear_search(arr, target): - for i in range(len(arr)): - if arr[i] == target: - return i - return -1 -``` - -## Binary Search - -Binary search is an efficient algorithm used for searching in sorted collections. It works by repeatedly dividing the search space in half until the target element is found or the search space is empty. - -```python -def binary_search(arr, target): - low = 0 - high = len(arr) - 1 - while low <= high: - mid = (low + high) // 2 - if arr[mid] == target: - return mid - elif arr[mid] < target: - low = mid + 1 - else: - high = mid - 1 - return -1 -``` - -## Hash-based Search - -Hash-based search utilizes a hash function to map keys to values in a data structure called a hash table. It provides constant-time average case complexity for searching. - -```python -hash_map = { - "apple": 1, - "banana": 2, - "orange": 3 -} - -value = hash_map.get("banana", -1) -print("Value:", value) -``` - -These are just a few examples of searching algorithms and their implementations in different programming languages. The choice of algorithm depends on factors such as the size of the data, whether it is sorted or unsorted, and the desired time complexity. - -Remember to provide appropriate input and handle edge cases when implementing these algorithms to ensure correct results. - -## Additional Questions - -1. **Question:** Implement a linear search algorithm in C++ to find the index of a target element in an array. Provide the input and output for the following scenario: - - **Input:** Array: [5, 2, 9, 7, 3], Target: 9 - - **Output:** Index: 2 - -```cpp -#include -using namespace std; - -int linearSearch(int arr[], int size, int target) { - for (int i = 0; i < size; i++) { - if (arr[i] == target) { - return i; - } - } - return -1; -} - -int main() { - int arr[] = {5, 2, 9, 7, 3}; - int target = 9; - int size = sizeof(arr) / sizeof(arr[0]); - int index = linearSearch(arr, size, target); - cout << "Index: " << index << endl; - return 0; -} -``` - -2. **Question:** Write a binary search algorithm in Java to find the index of a target element in a sorted array. Provide the input and output for the following scenario: - - **Input:** Array: [1, 3, 5, 7, 9], Target: 5 - - **Output:** Index: 2 - -```java -public class BinarySearch { - public static int binarySearch(int[] arr, int target) { - int low = 0; - int high = arr.length - 1; - while (low <= high) { - int mid = (low + high) / 2; - if (arr[mid] == target) { - return mid; - } else if (arr[mid] < target) { - low = mid + 1; - } else { - high = mid - 1; - } - } - return -1; - } - - public static void main(String[] args) { - int[] arr = {1, 3, 5, 7, 9}; - int target = 5; - int index = binarySearch(arr, target); - System.out.println("Index: " + index); - } -} -``` - -3. **Question:** Implement a hash-based search algorithm in Python to retrieve the value associated with a given key in a dictionary. Provide the input and output for the following scenario: - - **Input:** Dictionary: `{"apple": 1, "banana": 2, "orange": 3}`, Key: "banana" - - **Output:** Value: 2 - -```python -hash_map = { - "apple": 1, - "banana": 2, - "orange": 3 -} - -key = "banana" -value = hash_map.get(key, -1) -print("Value:", value) -``` - -Remember to provide appropriate input and handle edge cases when implementing these algorithms to ensure correct results. - -In conclusion, searching is a fundamental operation in computer science and is widely used in various applications. In the context of Data Structures and Algorithms (DSA), there are several types of searching algorithms, including linear search, binary search, and hash-based search. Each algorithm has its own characteristics and is suitable for different scenarios. - -Linear search is a simple algorithm that sequentially checks each element in a collection until the target element is found or the end of the collection is reached. It is commonly used for small collections or unsorted data. - -Binary search is an efficient algorithm used for searching in sorted collections. It works by repeatedly dividing the search space in half until the target element is found or the search space is empty. - -Hash-based search utilizes a hash function to map keys to values in a data structure called a hash table. It provides constant-time average case complexity for searching. - -When implementing these algorithms, it is important to provide appropriate input and handle edge cases to ensure correct results. - -Overall, understanding and implementing different searching algorithms is crucial for efficient data retrieval and manipulation in various programming scenarios. - -Searching is a fundamental operation in computer science and is widely used in various applications. In the context of Data Structures and Algorithms (DSA), searching refers to the process of finding a specific element within a collection of data. - -There are several types of searching algorithms commonly used in DSA, including linear search, binary search, hash-based search, and tree-based search. Each algorithm has its own characteristics and is suitable for different scenarios. - -Linear Search: - -Linear search is a simple algorithm that sequentially checks each element in a collection until the target element is found or the end of the collection is reached. -It is commonly used for small collections or unsorted data. -Here's an example of implementing linear search in JavaScript: -Binary Search: - -Binary search is an efficient algorithm used for searching in sorted collections. -It works by repeatedly dividing the search space in half until the target element is found or the search space is empty. -Here's an example of implementing binary search in Python: -Hash-based Search: - -Hash-based search utilizes a hash function to map keys to values in a data structure called a hash table. -It provides constant-time average case complexity for searching. -Here's an example of implementing hash-based search in Java using a HashMap: -These are just a few examples of searching algorithms and their implementations in different programming languages. The choice of algorithm depends on factors such as the size of the data, whether it is sorted or unsorted, and the desired time complexity. - -Remember to provide appropriate input and handle edge cases when implementing these algorithms to ensure correct results. diff --git a/docs/dsa/algorithms/sorting_algorithm.md b/docs/dsa/algorithms/sorting_algorithm.md deleted file mode 100644 index 9c37688d9..000000000 --- a/docs/dsa/algorithms/sorting_algorithm.md +++ /dev/null @@ -1,208 +0,0 @@ ---- -id: sorting-in-dsa -title: Sorting in Data Structures and Algorithms -sidebar_label: Sorting Algorithm -sidebar_position: 1 -description: "" -tags: - [dsa,data-algorithms , sorting - ] ---- - - - -Sorting is a fundamental operation in computer science that arranges a collection of elements in a specific order. There are various sorting algorithms available, each with its own advantages and disadvantages. In this section, we will explore some commonly used sorting algorithms and provide Python code examples for their implementation. - -![alt text](image-2.png) - -### 1. Bubble Sort - -Bubble Sort is a simple comparison-based sorting algorithm. It repeatedly compares adjacent elements and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted. - -```python -def bubble_sort(arr): - n = len(arr) - for i in range(n): - for j in range(0, n-i-1): - if arr[j] > arr[j+1]: - arr[j], arr[j+1] = arr[j+1], arr[j] -``` - -### 2. Selection Sort - -Selection Sort is another simple comparison-based sorting algorithm. It divides the input list into two parts: the sorted part at the left end and the unsorted part at the right end. It repeatedly selects the smallest element from the unsorted part and swaps it with the leftmost element of the unsorted part. - -```python -def selection_sort(arr): - n = len(arr) - for i in range(n): - min_idx = i - for j in range(i+1, n): - if arr[j] < arr[min_idx]: - min_idx = j - arr[i], arr[min_idx] = arr[min_idx], arr[i] -``` - -### 3. Insertion Sort - -Insertion Sort is an efficient comparison-based sorting algorithm that builds the final sorted array one element at a time. It iterates through the input list and for each element, it finds its correct position in the sorted part of the list and shifts the larger elements to the right. - -```python -def insertion_sort(arr): - n = len(arr) - for i in range(1, n): - key = arr[i] - j = i - 1 - while j >= 0 and arr[j] > key: - arr[j+1] = arr[j] - j -= 1 - arr[j+1] = key -``` - -### 4. Merge Sort - -Merge Sort is a divide-and-conquer sorting algorithm that divides the input list into smaller sublists, sorts them, and then merges them to obtain a sorted list. It recursively divides the list until each sublist contains only one element, and then merges the sublists in a sorted manner. - -```python -def merge_sort(arr): - if len(arr) <= 1: - return arr - - mid = len(arr) // 2 - left = arr[:mid] - right = arr[mid:] - - left = merge_sort(left) - right = merge_sort(right) - - return merge(left, right) - -def merge(left, right): - result = [] - i = j = 0 - - while i < len(left) and j < len(right): - if left[i] < right[j]: - result.append(left[i]) - i += 1 - else: - result.append(right[j]) - j += 1 - - while i < len(left): - result.append(left[i]) - i += 1 - - while j < len(right): - result.append(right[j]) - j += 1 - - return result -``` - -### 5. Quick Sort - -Quick Sort is a divide-and-conquer sorting algorithm that selects a pivot element and partitions the input list into two sublists, one with elements smaller than the pivot and one with elements greater than the pivot. It then recursively sorts the sublists. - -```python -def quick_sort(arr): - if len(arr) <= 1: - return arr - - pivot = arr[len(arr) // 2] - left = [x for x in arr if x < pivot] - middle = [x for x in arr if x == pivot] - right = [x for x in arr if x > pivot] - - return quick_sort(left) + middle + quick_sort(right) -``` - -### 6. Heap Sort - -Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It first builds a max heap from the input list, then repeatedly extracts the maximum element from the heap and places it at the end of the sorted list. - -```python -def heap_sort(arr): - n = len(arr) - - for i in range(n // 2 - 1, -1, -1): - heapify(arr, n, i) - - for i in range(n - 1, 0, -1): - arr[i], arr[0] = arr[0], arr[i] - heapify(arr, i, 0) - -def heapify(arr, n, i): - largest = i - left = 2 * i + 1 - right = 2 * i + 2 - - if left < n and arr[left] > arr[largest]: - largest = left - - if right < n and arr[right] > arr[largest]: - largest = right - - if largest != i: - arr[i], arr[largest] = arr[largest], arr[i] - heapify(arr, n, largest) -``` - - -### 7. Radix Sort - -Radix Sort is a non-comparative sorting algorithm that sorts integers by grouping them by individual digits. It starts by sorting the numbers based on the least significant digit and progressively moves towards the most significant digit. This process is repeated until the numbers are sorted based on all digits. - -```python -def radix_sort(arr): - # Find the maximum number to determine the number of digits - max_num = max(arr) - - # Perform counting sort for every digit - exp = 1 - while max_num // exp > 0: - counting_sort(arr, exp) - exp *= 10 - -def counting_sort(arr, exp): - n = len(arr) - output = [0] * n - count = [0] * 10 - - # Count the occurrences of each digit - for i in range(n): - index = arr[i] // exp - count[index % 10] += 1 - - # Calculate the cumulative count - for i in range(1, 10): - count[i] += count[i - 1] - - # Build the output array - i = n - 1 - while i >= 0: - index = arr[i] // exp - output[count[index % 10] - 1] = arr[i] - count[index % 10] -= 1 - i -= 1 - - # Copy the sorted elements back to the original array - for i in range(n): - arr[i] = output[i] -``` - -Radix Sort has a time complexity of O(d * (n + k)), where d is the number of digits, n is the number of elements, and k is the range of values. It is often used for sorting integers with a fixed number of digits. - -![alt text](image-1.png) - -### Conclusion - -In this article, we explored various sorting algorithms commonly used in data structures and algorithms. We provided Python code examples for each algorithm, including Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort, Heap Sort, and Radix Sort. - -Each sorting algorithm has its own advantages and disadvantages, and the choice of algorithm depends on the specific requirements of the problem at hand. It's important to consider factors such as time complexity, space complexity, stability, and adaptability when selecting a sorting algorithm. - -By understanding these sorting algorithms and their implementations, you can effectively organize and arrange collections of elements in a specific order, which is a fundamental operation in computer science. - -Remember to analyze the problem, consider the constraints, and choose the most appropriate sorting algorithm for your specific use case. - -Happy sorting! diff --git a/docs/dsa/arrays/_category_.json b/docs/dsa/arrays/_category_.json deleted file mode 100644 index e794c3655..000000000 --- a/docs/dsa/arrays/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Arrays", - "position": 6, - "link": { - "type": "generated-index", - "description": "In Data Structures, an array is a data structure consisting of a collection of elements, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. The simplest type of data structure is a linear array, also called one-dimensional array." - } - } \ No newline at end of file diff --git a/docs/dsa/arrays/arrays-bubblesort-dsa.md b/docs/dsa/arrays/arrays-bubblesort-dsa.md deleted file mode 100644 index 2da836dbb..000000000 --- a/docs/dsa/arrays/arrays-bubblesort-dsa.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -id: arrays-bubblesort-in-dsa -title: Arrays - Bubble Sort in DSA -sidebar_label: Bubble Sort -sidebar_position: 2 -description: "Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements 'bubble' to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position." -tags: [dsa, arrays, sorting, bubble-sort, algorithm of bubble-sort, pseudocode of bubble-sort, complexity of bubble-sort, example of bubble-sort, live example of bubble-sort, explanation of bubble-sort, quiz of bubble-sort, conclusion of bubble-sort] ---- - -**Bubble Sort** is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements bubble to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sorted order but may occasionally have some out-of-order elements nearly in position. - - - - -## Algorithm - -1. Start from the first element, compare the current element with the next element of the array. -2. If the current element is greater than the next element of the array, swap them. -3. If the current element is less than the next element, move to the next element. -4. Repeat steps 1-3 until the array is sorted. -5. The array is sorted. -6. Exit. -7. The time complexity of the bubble sort is O(n2). -8. The space complexity of the bubble sort is O(1). - -## Pseudocode - -```plaintext title="Bubble Sort" -procedure bubbleSort( A : list of sortable items ) - n = length(A) - repeat - swapped = false - for i = 1 to n-1 inclusive do - if A[i-1] > A[i] then - swap(A[i-1], A[i]) - swapped = true - end if - end for - until not swapped -end procedure -``` - -## Diagram - -```mermaid -graph TD - A([Start]) --> B("i = 0") - B --> C{"i < n-1"} - C -->|True| D("j = 0") - D --> E{"j < n - i - 1"} - E -->|True| F{arr j > arr j+1} - F -->|True| G{Swap arr j, arr j+1 } - G --> H{Increment j} - H --> |j++| D - F -->|False| I{Increment j} - I --> |j++| D - E --> |false i++| C - D --> |False| J{Increment i} - J --> |i++| C - C -->|False| K(Sorted Array) - K --> L([Stop]) - -``` - -## Example - -```js title="Bubble Sort" -function bubbleSort(arr) { - let n = arr.length; - let swapped; - do { - swapped = false; - for (let i = 0; i < n - 1; i++) { - if (arr[i] > arr[i + 1]) { - let temp = arr[i]; - arr[i] = arr[i + 1]; - arr[i + 1] = temp; - swapped = true; - } - } - } while (swapped); - return arr; -} - -let arr = [64, 34, 25, 12, 22, 11, 90]; -console.log(bubbleSort(arr)); // [ 11, 12, 22, 25, 34, 64, 90 ] -``` - -## Complexity - -- **Time Complexity**: O(n2) - - Best Case: O(n) - - Average Case: O(n2) - - Worst Case: O(n2) -- **Space Complexity**: O(1) -- **Stable**: Yes - -## Live Example - -```js live -function bubbleSort() { - let arr = [64, 34, 25, 12, 22, 11, 90]; - let n = arr.length; - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n - i - 1; j++) { - if (arr[j] > arr[j + 1]) { - let temp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = temp; - } - } - } - - return ( -
-

Bubble Sort

-

Array: [64, 34, 25, 12, 22, 11, 90]

-

- Sorted Array: [{arr.join(", ")}] -

-
- ) -} -``` - -## Explanation - -In the above example, we have an array of numbers `[64, 34, 25, 12, 22, 11, 90]`. We are using the bubble sort algorithm to sort the array in ascending order. The bubble sort algorithm compares each pair of adjacent items and swaps them if they are in the wrong order. The algorithm repeats this process until the array is sorted. The sorted array is `[11, 12, 22, 25, 34, 64, 90]`. The time complexity of the bubble sort is O(n2) and the space complexity is O(1). - -:::info Try it yourself -Change the array values and see how the bubble sort algorithm sorts the array. -::: - -:::tip 📝 Note -Bubble sort is not a practical sorting algorithm when the input is large. It is not suitable for large datasets due to its O(n2) time complexity. - -The main advantage of bubble sort is that it is easy to understand and implement. It is often used to teach the concept of sorting algorithms. - -Bubble sort is stable, meaning that it preserves the relative order of equal elements. - -Bubble sort is not an efficient algorithm for large datasets and is generally not used in practice. - -::: - -## References - -- [Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort) -- [GeeksforGeeks](https://www.geeksforgeeks.org/bubble-sort/) -- [Programiz](https://www.programiz.com/dsa/bubble-sort) -- [TutorialsPoint](https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm) -- [StudyTonight](https://www.studytonight.com/data-structures/bubble-sort) -- [w3schools](https://www.w3schools.com/dsa/dsa_algo_bubblesort.php) - -## Related - -Insertion Sort, Selection Sort, Merge Sort, Quick Sort, etc. - - -## Quiz - -1. What is the time complexity of the bubble sort algorithm? - - [ ] O(n) - - [x] O(n2) ✔ - - [ ] O(log n) - - [ ] O(n!) - -2. Is bubble sort a stable sorting algorithm? - - [x] Yes ✔ - - [ ] No - - [ ] Maybe - - [ ] Not sure - -3. What is the space complexity of the bubble sort algorithm? - - [ ] O(n) - - [x] O(1) ✔ - - [ ] O(log n) - - [ ] O(n!) - -4. What is the main advantage of bubble sort? - - [ ] It is the fastest sorting algorithm - - [x] It is easy to understand and implement ✔ - - [ ] It is suitable for large datasets - - [ ] It is used in practice - -5. What is the main disadvantage of bubble sort? - - [ ] It is the fastest sorting algorithm - - [ ] It is easy to understand and implement - - [x] It is not suitable for large datasets ✔ - - [ ] It is used in practice - -## Conclusion - -In this tutorial, we learned about the bubble sort algorithm. We discussed the algorithm, pseudocode, diagram, example, complexity, and related concepts. We also implemented the bubble sort algorithm in JavaScript and saw a live example. We also discussed the advantages and disadvantages of the bubble sort algorithm. We hope you enjoyed this tutorial and found it helpful. Feel free to share your thoughts in the comments below. \ No newline at end of file diff --git a/docs/dsa/arrays/arrays-dsa.md b/docs/dsa/arrays/arrays-dsa.md deleted file mode 100644 index ce8da614f..000000000 --- a/docs/dsa/arrays/arrays-dsa.md +++ /dev/null @@ -1,584 +0,0 @@ ---- -id: arrays-in-dsa -title: Arrays in Data Structures and Algorithms -sidebar_label: Arrays -sidebar_position: 1 -description: "An array is a collection of items stored at contiguous memory locations. It is a data structure that stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type." -tags: [dsa, data-structures, arrays, array, array-data-structure, array-in-dsa, array-in-data-structure, array-in-algorithm, array-in-dsa-example, array-in-dsa-explanation, array-in-dsa-conclusion, array-in-dsa-importance, array-in-dsa-syntax, array-in-dsa-declaration, array-in-dsa-access, array-in-dsa-update, array-in-dsa-length, array-in-dsa-iterate, array-in-dsa-max-min, array-in-dsa-program, array-in-dsa-code, array-in-dsa-js, array-in-dsa-java, array-in-dsa-python, array-in-dsa-c, array-in-dsa-cpp, array-in-dsa-ts] ---- - -An array is a collection of items stored at contiguous memory locations. It is a data structure that stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. - -## Visualizations of Arrays in Data Structures and Algorithms (DSA) - - - -## Why are Arrays important? - -Arrays are important because they allow us to store multiple items of the same type in a single variable. They are used to store data in a structured way, and they are used in many algorithms and data structures. - -## How to declare an Array? - -An array can be declared in various programming languages using the following syntax: - - - - - ```js - // Declare an array in JavaScript - let arr = [1, 2, 3, 4, 5]; - ``` - - - - ```java - // Declare an array in Java - int[] arr = {1, 2, 3, 4, 5}; - ``` - - - - ```python - # Declare an array in Python - arr = [1, 2, 3, 4, 5] - ``` - - - - ```c - // Declare an array in C - int arr[] = {1, 2, 3, 4, 5}; - ``` - - - - ```cpp - // Declare an array in C++ - int arr[] = {1, 2, 3, 4, 5}; - ``` - - - - ```ts - // Declare an array in TypeScript - let arr: number[] = [1, 2, 3, 4, 5]; - ``` - - - -## How to access an Array? - -An array can be accessed using the index of the element. The index of the first element is 0, the index of the second element is 1, and so on. - - - - - ```js - // Access an array in JavaScript - let arr = [1, 2, 3, 4, 5]; - console.log(arr[0]); // 1 - console.log(arr[1]); // 2 - console.log(arr[2]); // 3 - console.log(arr[3]); // 4 - console.log(arr[4]); // 5 - ``` - - - - ```java - // Access an array in Java - int[] arr = {1, 2, 3, 4, 5}; - System.out.println(arr[0]); // 1 - System.out.println(arr[1]); // 2 - System.out.println(arr[2]); // 3 - System.out.println(arr[3]); // 4 - System.out.println(arr[4]); // 5 - ``` - - - - ```python - # Access an array in Python - arr = [1, 2, 3, 4, 5] - print(arr[0]) # 1 - print(arr[1]) # 2 - print(arr[2]) # 3 - print(arr[3]) # 4 - print(arr[4]) # 5 - ``` - - - - ```c - // Access an array in C - int arr[] = {1, 2, 3, 4, 5}; - printf("%d\n", arr[0]); // 1 - printf("%d\n", arr[1]); // 2 - printf("%d\n", arr[2]); // 3 - printf("%d\n", arr[3]); // 4 - printf("%d\n", arr[4]); // 5 - ``` - - - - ```cpp - // Access an array in C++ - int arr[] = {1, 2, 3, 4, 5}; - cout << arr[0] << endl; // 1 - cout << arr[1] << endl; // 2 - cout << arr[2] << endl; // 3 - cout << arr[3] << endl; // 4 - cout << arr[4] << endl; // 5 - ``` - - - - ```ts - // Access an array in TypeScript - let arr: number[] = [1, 2, 3, 4, 5]; - console.log(arr[0]); // 1 - console.log(arr[1]); // 2 - console.log(arr[2]); // 3 - console.log(arr[3]); // 4 - console.log(arr[4]); // 5 - ``` - - - -## How to update an Array? - -An array can be updated by assigning a new value to the index of the element. - - - - - ```js - // Update an array in JavaScript - let arr = [1, 2, 3, 4, 5]; - arr[0] = 10; - console.log(arr); // [10, 2, 3, 4, 5] - ``` - - - - ```java - // Update an array in Java - int[] arr = {1, 2, 3, 4, 5}; - arr[0] = 10; - System.out.println(Arrays.toString(arr)); // [10, 2, 3, 4, 5] - ``` - - - - ```python - # Update an array in Python - arr = [1, 2, 3, 4, 5] - arr[0] = 10 - print(arr) # [10, 2, 3, 4, 5] - ``` - - - - ```c - // Update an array in C - int arr[] = {1, 2, 3, 4, 5}; - arr[0] = 10; - for (int i = 0; i < 5; i++) { - printf("%d ", arr[i]); - } - // 10 2 3 4 5 - ``` - - - - ```cpp - // Update an array in C++ - int arr[] = {1, 2, 3, 4, 5}; - arr[0] = 10; - for (int i = 0; i < 5; i++) { - cout << arr[i] << " "; - } - // 10 2 3 4 5 - ``` - - - - ```ts - // Update an array in TypeScript - let arr: number[] = [1, 2, 3, 4, 5]; - arr[0] = 10; - console.log(arr); // [10, 2, 3, 4, 5] - ``` - - - -## How to find the length of an Array? - -The length of an array can be found using the `length` property. - - - - - ```js - // Find the length of an array in JavaScript - let arr = [1, 2, 3, 4, 5]; - console.log(arr.length); // 5 - ``` - - - - ```java - // Find the length of an array in Java - int[] arr = {1, 2, 3, 4, 5}; - System.out.println(arr.length); // 5 - ``` - - - - ```python - # Find the length of an array in Python - arr = [1, 2, 3, 4, 5] - print(len(arr)) # 5 - ``` - - - - ```c - // Find the length of an array in C - int arr[] = {1, 2, 3, 4, 5}; - int length = sizeof(arr) // sizeof(arr[0]); - printf("%d\n", length); // 5 - ``` - - - - ```cpp - // Find the length of an array in C++ - int arr[] = {1, 2, 3, 4, 5}; - int length = sizeof(arr) // sizeof(arr[0]); - cout << length << endl; // 5 - ``` - - - - ```ts - // Find the length of an array in TypeScript - let arr: number[] = [1, 2, 3, 4, 5]; - console.log(arr.length); // 5 - ``` - - - -## How to iterate through an Array? - -An array can be iterated using a loop such as `for` loop, `while` loop, or `for...of` loop. - - - - - ```js - // Iterate through an array in JavaScript - let arr = [1, 2, 3, 4, 5]; - for (let i = 0; i < arr.length; i++) { - console.log(arr[i]); - } - // 1 - // 2 - // 3 - // 4 - // 5 - ``` - - - - ```java - // Iterate through an array in Java - int[] arr = {1, 2, 3, 4, 5}; - for (int i = 0; i < arr.length; i++) { - System.out.println(arr[i]); - } - // 1 - // 2 - // 3 - // 4 - // 5 - ``` - - - - ```python - # Iterate through an array in Python - arr = [1, 2, 3, 4, 5] - for i in arr: - print(i) - # 1 - # 2 - # 3 - # 4 - # 5 - ``` - - - - ```c - // Iterate through an array in C - int arr[] = {1, 2, 3, 4, 5}; - for (int i = 0; i < 5; i++) { - printf("%d\n", arr[i]); - } - // 1 - // 2 - // 3 - // 4 - // 5 - ``` - - - - ```cpp - // Iterate through an array in C++ - int arr[] = {1, 2, 3, 4, 5}; - for (int i = 0; i < 5; i++) { - cout << arr[i] << endl; - } - // 1 - // 2 - // 3 - // 4 - // 5 - ``` - - - - ```ts - // Iterate through an array in TypeScript - let arr: number[] = [1, 2, 3, 4, 5]; - for (let i = 0; i < arr.length; i++) { - console.log(arr[i]); - } - // 1 - // 2 - // 3 - // 4 - // 5 - ``` - - - -## How to find the maximum and minimum elements in an Array? - -The maximum and minimum elements in an array can be found by iterating through the array and comparing each element with the current maximum and minimum elements. - - - - - ```js - // Find the maximum and minimum elements in an array in JavaScript - function findMaxMin(arr) { - let max = arr[0]; - let min = arr[0]; - for (let i = 1; i < arr.length; i++) { - if (arr[i] > max) { - max = arr[i]; - } - if (arr[i] < min) { - min = arr[i]; - } - } - return { max, min }; - } - - let arr = [2, 5, 1, 20, 10]; - console.log(findMaxMin(arr)); // { max: 20, min: 1 } - ``` - - - - ```java - public class Main { - // Find the maximum and minimum elements in an array in Java - static class MaxMin { - int max; - int min; - } - - static MaxMin findMaxMin(int arr[]) { - MaxMin result = new MaxMin(); - result.max = arr[0]; - result.min = arr[0]; - for (int i = 1; i < arr.length; i++) { - if (arr[i] > result.max) { - result.max = arr[i]; - } - if (arr[i] < result.min) { - result.min = arr[i]; - } - } - return result; - } - - public static void main(String[] args) { - int arr[] = {2, 5, 1, 20, 10}; - MaxMin result = findMaxMin(arr); - System.out.println("{ max: " + result.max + ", min: " + result.min + " }"); // { max: 20, min: 1 } - } - } - - ``` - - - - ```python - # Find the maximum and minimum elements in an array in Python - def find_max_min(arr): - max = arr[0] - min = arr[0] - for i in range(1, len(arr)): - if arr[i] > max: - max = arr[i] - if arr[i] < min: - min = arr[i] - return {"max": max, "min": min} - - arr = [2, 5, 1, 20, 10] - print(find_max_min(arr)) # { max: 20, min: 1 } - ``` - - - - ```c - // Find the maximum and minimum elements in an array in C - struct MaxMin { - int max; - int min; - }; - - struct MaxMin findMaxMin(int arr[], int n) { - struct MaxMin result; - result.max = arr[0]; - result.min = arr[0]; - for (int i = 1; i < n; i++) { - if (arr[i] > result.max) { - result.max = arr[i]; - } - if (arr[i] < result.min) { - result.min = arr[i]; - } - } - return result; - } - - int arr[] = {2, 5, 1, 20, 10}; - struct MaxMin result = findMaxMin(arr, 5); - printf("{ max: %d, min: %d }\n", result.max, result.min); // { max: 20, min: 1 } - ``` - - - - ```cpp - // Find the maximum and minimum elements in an array in C++ - struct MaxMin { - int max; - int min; - }; - - MaxMin findMaxMin(int arr[], int n) { - MaxMin result; - result.max = arr[0]; - result.min = arr[0]; - for (int i = 1; i < n; i++) { - if (arr[i] > result.max) { - result.max = arr[i]; - } - if (arr[i] < result.min) { - result.min = arr[i]; - } - } - return result; - } - - int arr[] = {2, 5, 1, 20, 10}; - MaxMin result = findMaxMin(arr, 5); - cout << "{ max: " << result.max << ", min: " << result.min << " }" << endl; // { max: 20, min: 1 } - ``` - - - - ```ts - // Find the maximum and minimum elements in an array in TypeScript - interface MaxMin { - max: number; - min: number; - } - - function findMaxMin(arr: number[]): MaxMin { - let max = arr[0]; - let min = arr[0]; - for (let i = 1; i < arr.length; i++) { - if (arr[i] > max) { - max = arr[i]; - } - if (arr[i] < min) { - min = arr[i]; - } - } - return { max, min }; - } - - let arr: number[] = [2, 5, 1, 20, 10]; - console.log(findMaxMin(arr)); // { max: 20, min: 1 } - ``` - - - -:::info 📝 Info -- The time complexity of finding the maximum and minimum elements in an array is O(n). -- The space complexity of finding the maximum and minimum elements in an array is O(1). -::: - -## Problems for Practice - -export const problems = [ - { - "problemName": "1. Two Sum", - "difficulty": "Easy", - "leetCodeLink": "https://leetcode.com/problems/two-sum/", - "solutionLink": "#" - }, - { - "problemName": "2. Best Time to Buy and Sell Stock", - "difficulty": "Easy", - "leetCodeLink": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/", - "solutionLink": "#" - }, - { - "problemName": "3. Contains Duplicate", - "difficulty": "Easy", - "leetCodeLink": "https://leetcode.com/problems/contains-duplicate/", - "solutionLink": "#" - }, - { - "problemName": "4. Product of Array Except Self", - "difficulty": "Medium", - "leetCodeLink": "https://leetcode.com/problems/product-of-array-except-self/", - "solutionLink": "#" - }, - { - "problemName": "5. Maximum Subarray", - "difficulty": "Easy", - "leetCodeLink": "https://leetcode.com/problems/maximum-subarray/", - "solutionLink": "#" - } - -] - - - -## Conclusion - -In this tutorial, we learned about arrays in data structures and algorithms. We learned how to declare an array, access an array, update an array, find the length of an array, iterate through an array, and find the maximum and minimum elements in an array. Arrays are an important data structure that is used in many algorithms and data structures. \ No newline at end of file diff --git a/docs/dsa/arrays/arrays-insertionsort.md b/docs/dsa/arrays/arrays-insertionsort.md deleted file mode 100644 index 02eeecee6..000000000 --- a/docs/dsa/arrays/arrays-insertionsort.md +++ /dev/null @@ -1,168 +0,0 @@ ---- -id: arrays-insertionsort -title: Arrays - Insertion Sort -sidebar_label: Insertion Sort -sidebar_position: 4 -description: "Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort." -tags: [dsa, arrays, sorting, insertion-sort, sorting-algorithms] ---- - -**Insertion Sort** is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. - -However, insertion sort provides several advantages: - -- **Simple implementation:** The code implementation of insertion sort is simple and easy to understand. -- **Efficient for small data sets:** Insertion sort is efficient for small data sets. -- **Adaptive:** It is adaptive, meaning it is efficient for data sets that are already substantially sorted. -- **Stable:** It is a stable sorting algorithm, meaning it preserves the relative order of equal elements. -- **In-place:** It requires only a constant amount of additional memory space. -- **Online:** It can sort a list as it receives it. -- **More efficient in practice:** It is more efficient in practice than other quadratic-time sorting algorithms like bubble sort and selection sort. -- **Simple to code:** It is simple to code and implement. - - - -
- -The insertion sort algorithm takes value at a time from the unsorted part and places it in its correct position in the sorted part. The sorted part is built from left to right, and the unsorted part is on the right side of the array. The algorithm works by shifting the elements in the sorted part that are greater than the current element to the right, creating space for the current element to be inserted. - -:::info Key Points -- **Type:** Sorting Algorithm -- **Time Complexity:** - - **Best Case:** *O(n)* - - **Average Case:** *O(n2)* - - **Worst Case:** *O(n2)* -- **Space Complexity:** *O(1)* -- **Stable:** Yes -- **In-Place:** Yes -- **Online:** Yes -- **Adaptive:** Yes -- **Comparison Sort:** Yes -- **Suitable for:** Small data sets, partially sorted data sets -- **Efficient for:** Small data sets -- **Not efficient for:** Large data sets -- **Simple to code:** Yes -- **Efficient in practice:** Yes - -::: - -:::tip Real-World Analogy -Insertion sort can be compared to sorting a deck of cards. You start with an empty hand and pick one card at a time from the deck. You then insert the card into its correct position in your hand, shifting the other cards if necessary. This process is repeated until all the cards are sorted in your hand. - -## How Insertion Sort Works? - -Let's understand how the Insertion Sort algorithm works with an example: - -Consider an array `arr = [12, 11, 13, 5, 6]` that we want to sort in ascending order using the Insertion Sort algorithm. - -1. **Initial Array:** `[12, 11, 13, 5, 6]` -2. **Step 1:** Start from the second element (index 1) and compare it with the previous element. - - Compare `11` with `12`. Since `11` is smaller, swap them. - - **Array after Step 1:** `[11, 12, 13, 5, 6]` - - The array is partially sorted from index 0 to 1. - - The current array looks like this: `[11, 12, 13, 5, 6]` - - The sorted part is `[11, 12]`, and the unsorted part is `[13, 5, 6]`. - - The key element is `13`. - - The key element is compared with the elements in the sorted part. - - Since `13` is greater than `12`, no swap is needed. - - The array remains the same: `[11, 12, 13, 5, 6]` - - The array is partially sorted from index 0 to 2. - - The current array looks like this: `[11, 12, 13, 5, 6]` - - The sorted part is `[11, 12, 13]`, and the unsorted part is `[5, 6]`. - - The key element is `5`. - - The key element is compared with the elements in the sorted part. - - Since `5` is smaller than `13`, `12`, and `11`, it is moved to the left. - - **Array after Step 1:** `[5, 11, 12, 13, 6]` - - The array is partially sorted from index 0 to 3. - - The current array looks like this: `[5, 11, 12, 13, 6]` - - The sorted part is `[5, 11, 12, 13]`, and the unsorted part is `[6]`. - - The key element is `6`. - - The key element is compared with the elements in the sorted part. - - Since `6` is smaller than `13`, it is moved to the left. - - Since `6` is smaller than `12`, it is moved to the left. - - Since `6` is smaller than `11`, it is moved to the left. - - **Array after Step 1:** `[5, 6, 11, 12, 13]` - - The array is now sorted. - - The sorted array is `[5, 6, 11, 12, 13]`. - -3. **Final Sorted Array:** `[5, 6, 11, 12, 13]` -4. The array is now sorted in ascending order using the Insertion Sort algorithm. -5. The time complexity of the Insertion Sort algorithm is ***O(n2)*** in the worst-case scenario. -6. The space complexity of the Insertion Sort algorithm is ***O(1)***. -7. The Insertion Sort algorithm is efficient for small data sets and partially sorted data sets. - -## Visualization - -You can visualize the Insertion Sort algorithm using the following animation: - -
- -
- -You can select the Insertion Sort algorithm from the drop-down menu and visualize how it works on different arrays. - -::: - -## Algorithm - -The insertion sort algorithm works as follows: - -1. Start from the second element (index 1) and compare it with the previous elements. -2. If the current element is smaller than the previous element, swap them. -3. Repeat this process until the current element is greater than the previous element or until the first element is reached. -4. Move to the next element and repeat the process. -5. Continue this process until the entire array is sorted. -6. The array is now sorted. -7. The time complexity of the insertion sort algorithm is ***O(n2)*** in the worst-case scenario. -8. The space complexity of the insertion sort algorithm is ***O(1)***. - -## Pseudocode - -```plaintext -1. for i = 1 to n-1 -2. key = arr[i] -3. j = i - 1 -4. while j >= 0 and arr[j] > key -5. arr[j + 1] = arr[j] -6. j = j - 1 -7. arr[j + 1] = key -``` - -## Implementation - -Here's the implementation of the Insertion Sort algorithm in JavaScript: - -```javascript title="Insertion Sort" -function insertionSort(arr) { - const n = arr.length; - for (let i = 1; i < n; i++) { - let key = arr[i]; - let j = i - 1; - while (j >= 0 && arr[j] > key) { - arr[j + 1] = arr[j]; - j = j - 1; - } - arr[j + 1] = key; - } - return arr; -} - -const arr = [12, 11, 13, 5, 6]; -console.log(insertionSort(arr)); // Output: [5, 6, 11, 12, 13] -``` - -## Complexity Analysis - -The time complexity of the Insertion Sort algorithm is ***O(n2)*** in the worst-case scenario when the array is sorted in reverse order. The best-case time complexity is ***O(n)*** when the array is already sorted. - -The space complexity of the Insertion Sort algorithm is ***O(1)*** since it requires only a constant amount of additional memory space. - -## References - -- [Wikipedia - Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) -- [GeeksforGeeks - Insertion Sort](https://www.geeksforgeeks.org/insertion-sort/) -- [Programiz - Insertion Sort](https://www.programiz.com/dsa/insertion-sort) -- [Khan Academy - Insertion Sort](https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/a/insertion-sort) -- [TutorialsPoint - Insertion Sort](https://www.tutorialspoint.com/data_structures_algorithms/insertion_sort_algorithm.htm) -- [StudyTonight - Insertion Sort](https://www.studytonight.com/data-structures/insertion-sorting) -- [Insertion Sort Visualization](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) \ No newline at end of file diff --git a/docs/dsa/arrays/arrays-selectionsort.md b/docs/dsa/arrays/arrays-selectionsort.md deleted file mode 100644 index 706040c34..000000000 --- a/docs/dsa/arrays/arrays-selectionsort.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -id: arrays-selectionsort-in-dsa -title: Arrays - Selection Sort in DSA -sidebar_label: Selection Sort -sidebar_position: 3 -description: "Selection Sort is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray." -tags: [dsa, arrays, sorting, selection-sort, algorithm of selection-sort, pseudocode of selection-sort, complexity of selection-sort, example of selection-sort, live example of selection-sort, explanation of selection-sort, quiz of selection-sort, conclusion of selection-sort] ---- - -**Selection Sort** is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray. - - - -## Algorithm - -1. The selection sort algorithm divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. -2. The algorithm repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. -3. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. -4. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray. -5. The array is sorted. -6. Exit. -7. The time complexity of the selection sort is O(n^2). -8. The space complexity of the selection sort is O(1). - -## Pseudocode - -```plaintext title="Selection Sort" -procedure selectionSort( A : list of sortable items ) - n = length(A) - for i = 0 to n-1 inclusive do - min = i - for j = i+1 to n inclusive do - if A[j] < A[min] then - min = j - end if - end for - swap(A[i], A[min]) - end for -end procedure -``` - -## Diagram - - -## Complexity - -The time complexity of the selection sort is O(n^2). The space complexity of the selection sort is O(1). - -## Example - -```js title="Selection Sort" -function selectionSort(arr) { - let n = arr.length; - for (let i = 0; i < n - 1; i++) { - let min = i; - for (let j = i + 1; j < n; j++) { - if (arr[j] < arr[min]) { - min = j; - } - } - let temp = arr[i]; - arr[i] = arr[min]; - arr[min] = temp; - } - return arr; -} - -const arr = [64, 25, 12, 22, 11]; - -console.log(selectionSort(arr)); // [11, 12, 22, 25, 64] -``` - -## Practice Problems - -- [Leetcode - Sort an Array](https://leetcode.com/problems/sort-an-array/) -- [HackerRank - The Full Counting Sort](https://www.hackerrank.com/challenges/countingsort4/problem) -- [Codeforces - Sort the Array](https://codeforces.com/problemset/problem/451/B) -- [CodeChef - Turbo Sort](https://www.codechef.com/problems/TSORT) - -## Quiz - -1. What is the time complexity of the selection sort? - - A) O(n) - - B) O(n^2) - - C) O(n log n) - - D) O(1) - - Correct Answer: B - -2. What is the space complexity of the selection sort? - - A) O(n) - - B) O(n^2) - - C) O(n log n) - - D) O(1) - - Correct Answer: D -- Explanation: The space complexity of the selection sort is O(1). - -3. What is the best-case time complexity of the selection sort? - - A) O(n) - - B) O(n^2) - - C) O(n log n) - - D) O(1) - - Correct Answer: B - -4. What is the worst-case time complexity of the selection sort? - - A) O(n) - - B) O(n^2) - - C) O(n log n) - - D) O(1) - - Correct Answer: B - -5. Is the selection sort stable? - - A) Yes - - B) No - - Correct Answer: A - - -:::info Try it yourself - -```js live -function selectionSort() { - let arr = [64, 25, 12, 22, 11]; - let n = arr.length; - for (let i = 0; i < n - 1; i++) { - let min = i; - for (let j = i + 1; j < n; j++) { - if (arr[j] < arr[min]) { - min = j; - } - } - let temp = arr[i]; - arr[i] = arr[min]; - arr[min] = temp; - } - return ( -
-

Selection Sort

-

Array: [64, 25, 12, 22, 11]

-

- Sorted Array: [{arr.join(", ")}] -

-
- ) -} -``` - -In the above example, we have an array of numbers `[64, 25, 12, 22, 11]`. We are using the selection sort algorithm to sort the array in ascending order. The selection sort algorithm divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray. The sorted array is `[11, 12, 22, 25, 64]`. The time complexity of the selection sort is O(n^2) and the space complexity is O(1). - -::: - -## Conclusion - -In this article, we learned about the selection sort algorithm. Selection sort is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray. The time complexity of the selection sort is O(n^2) and the space complexity is O(1). Selection sort is a stable sorting algorithm. \ No newline at end of file diff --git a/docs/dsa/arrays/bucket-sort.md b/docs/dsa/arrays/bucket-sort.md deleted file mode 100644 index 8067ac6d2..000000000 --- a/docs/dsa/arrays/bucket-sort.md +++ /dev/null @@ -1,204 +0,0 @@ ---- -id: bucket-sort -title: Bucket sort -sidebar_label: Bucket sort -tags: - - DSA - - Python - - C++ - - Java - - Sorting - -description: "Thsi page containes Bucket Sort, with codes in python, java and c++ " ---- - -### Introduction to Bucket Sort - -Bucket sort is a comparison sorting algorithm that distributes elements into a number of "buckets." Each bucket is then sorted individually, either using another sorting algorithm or recursively applying the bucket sort. Finally, the sorted buckets are combined to form the final sorted array. Bucket sort is particularly useful for uniformly distributed data. - -### Steps of Bucket Sort - -1. **Create Buckets**: Initialize an empty array of buckets. -2. **Distribute Elements**: Distribute the elements of the input array into the appropriate buckets. -3. **Sort Buckets**: Sort each bucket individually. -4. **Concatenate Buckets**: Concatenate all sorted buckets to form the final sorted array. - -### Pseudocode - -```text -function bucketSort(array, bucketSize): - if length(array) == 0: - return array - - // Determine minimum and maximum values - minValue = min(array) - maxValue = max(array) - - // Initialize buckets - bucketCount = floor((maxValue - minValue) / bucketSize) + 1 - buckets = array of empty lists of size bucketCount - - // Distribute input array values into buckets - for i from 0 to length(array) - 1: - bucketIndex = floor((array[i] - minValue) / bucketSize) - append array[i] to buckets[bucketIndex] - - // Sort each bucket and concatenate them - sortedArray = [] - for i from 0 to bucketCount - 1: - sort(buckets[i]) // You can use any sorting algorithm - append buckets[i] to sortedArray - - return sortedArray -``` - -### Implementation in Python, C++, and Java - -#### Python Implementation - -```python -def bucket_sort(numbers, size=5): - if len(numbers) == 0: - return numbers - - # Determine minimum and maximum values - min_value = min(numbers) - max_value = max(numbers) - - # Initialize buckets - bucket_count = (max_value - min_value) // size + 1 - buckets = [[] for _ in range(bucket_count)] - - # Distribute input array values into buckets - for number in numbers: - bucket_index = (number - min_value) // size - buckets[bucket_index].append(number) - - # Sort each bucket and concatenate them - sorted_numbers = [] - for bucket in buckets: - sorted_numbers.extend(sorted(bucket)) - - return sorted_numbers - -# Example usage -data = [42, 32, 33, 52, 37, 47, 51] -sorted_data = bucket_sort(data) -print(sorted_data) # Output: [32, 33, 37, 42, 47, 51, 52] -``` - -#### C++ Implementation - -```cpp -#include -#include -#include -using namespace std; - -void bucketSort(vector& nums, int bucketSize) { - if (nums.empty()) - return; - - // Determine minimum and maximum values - int minValue = *min_element(nums.begin(), nums.end()); - int maxValue = *max_element(nums.begin(), nums.end()); - - // Initialize buckets - int numBuckets = (maxValue - minValue) / bucketSize + 1; - vector> buckets(numBuckets); - - // Distribute input array values into buckets - for (int num : nums) { - int bucketIndex = (num - minValue) / bucketSize; - buckets[bucketIndex].push_back(num); - } - - // Sort each bucket and concatenate them - nums.clear(); - for (auto& bucket : buckets) { - sort(bucket.begin(), bucket.end()); - nums.insert(nums.end(), bucket.begin(), bucket.end()); - } -} - -// Example usage -int main() { - vector data = {42, 32, 33, 52, 37, 47, 51}; - bucketSort(data, 5); - for (int num : data) { - cout << num << " "; - } - // Output: 32 33 37 42 47 51 52 - return 0; -} -``` - -#### Java Implementation - -```java -import java.util.ArrayList; -import java.util.Collections; - -public class BucketSort { - public static void bucketSort(int[] array, int bucketSize) { - if (array.length == 0) - return; - - // Determine minimum and maximum values - int minValue = array[0]; - int maxValue = array[0]; - for (int num : array) { - if (num < minValue) - minValue = num; - else if (num > maxValue) - maxValue = num; - } - - // Initialize buckets - int bucketCount = (maxValue - minValue) / bucketSize + 1; - ArrayList> buckets = new ArrayList<>(bucketCount); - for (int i = 0; i < bucketCount; i++) { - buckets.add(new ArrayList()); - } - - // Distribute input array values into buckets - for (int num : array) { - int bucketIndex = (num - minValue) / bucketSize; - buckets.get(bucketIndex).add(num); - } - - // Sort each bucket and concatenate them - int currentIndex = 0; - for (ArrayList bucket : buckets) { - Collections.sort(bucket); - for (int num : bucket) { - array[currentIndex++] = num; - } - } - } - - // Example usage - public static void main(String[] args) { - int[] data = {42, 32, 33, 52, 37, 47, 51}; - bucketSort(data, 5); - for (int num : data) { - System.out.print(num + " "); - } - // Output: 32 33 37 42 47 51 52 - } -} -``` - -### Complexity - -- **Time Complexity**: - - - Best Case: $O(n + k)$, where $n$ is the number of elements and $k$ is the number of buckets. - - Average Case: $O(n + k + n \log(\frac{n}{k}))$ - - Worst Case: $O(n^2)$, when all elements are placed in one bucket and a slow sorting algorithm (like bubble sort) is used within buckets. - -- **Space Complexity**: $O(n + k)$, for the input array and the buckets. - -### Conclusion - -Bucket sort is efficient for sorting uniformly distributed data and can achieve linear time complexity in the best case. However, it may degrade to quadratic time complexity in the worst case if elements are not uniformly distributed. It's essential to choose an appropriate bucket size and secondary sorting algorithm for optimal performance. By understanding its structure and implementation, you can effectively use bucket sort for various sorting tasks. diff --git a/docs/dsa/arrays/radix-sort.md b/docs/dsa/arrays/radix-sort.md deleted file mode 100644 index a360eed45..000000000 --- a/docs/dsa/arrays/radix-sort.md +++ /dev/null @@ -1,261 +0,0 @@ ---- -id: radix-sort -title: Radix sort -sidebar_label: Radix Sort -tags: - - DSA - - Python - - C++ - - Java - - Sorting - -description: "This page explains Radix sort, with code implementations and resources for further learning." ---- - -# Radix Sort - -### Introduction to Radix Sort - -Radix sort is a non-comparative integer sorting algorithm. It sorts integers by processing individual digits. Starting from the least significant digit (LSD) to the most significant digit (MSD), it uses a stable subroutine sort (like counting sort) to handle the individual digits. The algorithm is efficient for sorting numbers with a fixed number of digits and works well when the range of digits is not excessively large. - -### Steps of Radix Sort (Pseudocode Steps) - -1. **Find the maximum number** to determine the number of digits. -2. **Initialize**: Set up a loop to process each digit from the least significant to the most significant. -3. **Digit by digit sorting**: - - Use a stable sort (e.g., counting sort) to sort based on the current digit. -4. **Repeat** until all digits are processed. - -### Example - -To perform radix sort on the array [170, 45, 75, 90, 802, 24, 2, 66], we follow these steps: -![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230609164537/Radix-Sort.png) - -Step 1: Find the largest element in the array, which is 802. It has three digits, so we will iterate three times, once for each significant place. - -Step 2: Sort the elements based on the unit place digits (X=0). We use a stable sorting technique, such as counting sort, to sort the digits at each significant place. - -Sorting based on the unit place: - -Perform counting sort on the array based on the unit place digits. -The sorted array based on the unit place is [170, 90, 802, 2, 24, 45, 75, 66]. - -![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230609164536/Radix-Sort--1.png) - -Step 3: Sort the elements based on the tens place digits. - -Sorting based on the tens place: - -Perform counting sort on the array based on the tens place digits. -The sorted array based on the tens place is [802, 2, 24, 45, 66, 170, 75, 90]. - -![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230609164535/Radix-Sort--2.png) - -Step 4: Sort the elements based on the hundreds place digits. - -Sorting based on the hundreds place: - -Perform counting sort on the array based on the hundreds place digits. -The sorted array based on the hundreds place is [2, 24, 45, 66, 75, 90, 170, 802]. - -![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230609164535/Radix-Sort--3.png) - -Step 5: The array is now sorted in ascending order. - -The final sorted array using radix sort is [2, 24, 45, 66, 75, 90, 170, 802]. - -![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230609164534/Radix-Sort--4.png) - -### Pseudocode for Radix Sort - -```text -function radixSort(array): - maxNumber = findMax(array) - numberOfDigits = countDigits(maxNumber) - - for digit in 1 to numberOfDigits: - countingSortByDigit(array, digit) - -function findMax(array): - maxNumber = array[0] - for number in array: - if number > maxNumber: - maxNumber = number - return maxNumber - -function countDigits(number): - count = 0 - while number != 0: - number = number // 10 - count += 1 - return count - -function countingSortByDigit(array, digit): - count = array of size 10 initialized to 0 - output = array of same size as input array - - # Count occurrences of each digit - for number in array: - digitValue = (number // 10^(digit - 1)) % 10 - count[digitValue] += 1 - - # Change count[i] so that count[i] contains the position of this digit in output - for i from 1 to 9: - count[i] += count[i - 1] - - # Build the output array - for i from length(array) - 1 to 0: - digitValue = (array[i] // 10^(digit - 1)) % 10 - output[count[digitValue] - 1] = array[i] - count[digitValue] -= 1 - - # Copy the output array to the input array - for i from 0 to length(array) - 1: - array[i] = output[i] -``` - -### Radix Sort Implementation in Python, C++, and Java - -#### Python - -```python -def radix_sort(array): - def counting_sort_by_digit(array, digit): - count = [0] * 10 - output = [0] * len(array) - - for number in array: - digit_value = (number // 10**(digit - 1)) % 10 - count[digit_value] += 1 - - for i in range(1, 10): - count[i] += count[i - 1] - - for i in range(len(array) - 1, -1, -1): - digit_value = (array[i] // 10**(digit - 1)) % 10 - output[count[digit_value] - 1] = array[i] - count[digit_value] -= 1 - - for i in range(len(array)): - array[i] = output[i] - - max_number = max(array) - number_of_digits = len(str(max_number)) - - for digit in range(1, number_of_digits + 1): - counting_sort_by_digit(array, digit) - -# Example usage -arr = [170, 45, 75, 90, 802, 24, 2, 66] -radix_sort(arr) -print(arr) -``` - -#### C++ - -```cpp -#include -#include -#include - -void countingSortByDigit(std::vector& array, int digit) { - int size = array.size(); - std::vector output(size); - int count[10] = {0}; - - for (int i = 0; i < size; i++) { - int digitValue = (array[i] / digit) % 10; - count[digitValue]++; - } - - for (int i = 1; i < 10; i++) { - count[i] += count[i - 1]; - } - - for (int i = size - 1; i >= 0; i--) { - int digitValue = (array[i] / digit) % 10; - output[count[digitValue] - 1] = array[i]; - count[digitValue]--; - } - - for (int i = 0; i < size; i++) { - array[i] = output[i]; - } -} - -void radixSort(std::vector& array) { - int maxNumber = *max_element(array.begin(), array.end()); - for (int digit = 1; maxNumber / digit > 0; digit *= 10) { - countingSortByDigit(array, digit); - } -} - -// Example usage -int main() { - std::vector arr = {170, 45, 75, 90, 802, 24, 2, 66}; - radixSort(arr); - for (int num : arr) { - std::cout << num << " "; - } - return 0; -} -``` - -#### Java - -```java -import java.util.Arrays; - -public class RadixSort { - - public static void radixSort(int[] array) { - int maxNumber = Arrays.stream(array).max().getAsInt(); - for (int digit = 1; maxNumber / digit > 0; digit *= 10) { - countingSortByDigit(array, digit); - } - } - - private static void countingSortByDigit(int[] array, int digit) { - int size = array.length; - int[] output = new int[size]; - int[] count = new int[10]; - - for (int i = 0; i < size; i++) { - int digitValue = (array[i] / digit) % 10; - count[digitValue]++; - } - - for (int i = 1; i < 10; i++) { - count[i] += count[i - 1]; - } - - for (int i = size - 1; i >= 0; i--) { - int digitValue = (array[i] / digit) % 10; - output[count[digitValue] - 1] = array[i]; - count[digitValue]--; - } - - for (int i = 0; i < size; i++) { - array[i] = output[i]; - } - } - - public static void main(String[] args) { - int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; - radixSort(arr); - System.out.println(Arrays.toString(arr)); - } -} -``` - -### Complexity of Radix Sort - -- **Time Complexity**: $O(d⋅(n+k))$ - - $d$: Number of digits in the largest number. - - $n$: Number of elements in the array. - - $k$: Range of the digits for decimal system, $k = 10.$ -- **Space Complexity**: $O(n + k)$ - -### Conclusion - -Radix sort is a powerful sorting algorithm for integers or fixed-length strings. Its efficiency and non-comparative nature make it a valuable tool for specific use cases, especially where the number of digits or characters is limited. Understanding and implementing radix sort can significantly enhance the performance of sorting operations in such scenarios. diff --git a/docs/dsa/basic-concepts/_category_.json b/docs/dsa/basic-concepts/_category_.json deleted file mode 100644 index b810bad9b..000000000 --- a/docs/dsa/basic-concepts/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Basic Concepts", - "position": 5, - "link": { - "type": "generated-index", - "description": "Basic Concepts of Data Structures and Algorithms." - } - } \ No newline at end of file diff --git a/docs/dsa/basic-concepts/image-1.png b/docs/dsa/basic-concepts/image-1.png deleted file mode 100644 index cd127aab3..000000000 Binary files a/docs/dsa/basic-concepts/image-1.png and /dev/null differ diff --git a/docs/dsa/basic-concepts/image.png b/docs/dsa/basic-concepts/image.png deleted file mode 100644 index 8a263334f..000000000 Binary files a/docs/dsa/basic-concepts/image.png and /dev/null differ diff --git a/docs/dsa/basic-concepts/space-complexity.md b/docs/dsa/basic-concepts/space-complexity.md deleted file mode 100644 index 8bf46a6ea..000000000 --- a/docs/dsa/basic-concepts/space-complexity.md +++ /dev/null @@ -1,212 +0,0 @@ ---- -id: space-complexity -title: Space Complexity -sidebar_label: Space Complexity -sidebar_position: 2 -description: "Space complexity is a measure of the amount of working storage an algorithm needs. It is a measure of the amount of memory space an algorithm needs to solve a problem as a function of the size of the input to the problem. It is the amount of memory space required by the algorithm to execute in its life cycle." -tags: [Space Complexity, Big O Notation, Memory, Algorithm, Complexity Analysis, Data Structure, DSA, JavaScript, Java, Python, C, C++, Space Complexity Example, Space Complexity Calculation, Space Complexity Analysis, Space Complexity Explanation, Space Complexity Conclusion, Space Complexity Importance, Space Complexity Formula, Space Complexity Constant Space, Space Complexity Auxiliary Space, Space Complexity Example, Space Complexity Program, Space Complexity Code] ---- - -Space complexity is a measure of the amount of working storage an algorithm needs. It is a measure of the amount of memory space an algorithm needs to solve a problem as a function of the size of the input to the problem. It is the amount of memory space required by the algorithm to execute in its life cycle. - -## Why is Space Complexity important? - -Space complexity is important because the memory that is allocated to the program is limited. If the program uses more memory than the available memory, the program will crash. Therefore, it is important to know the space complexity of the algorithm. - -## How to calculate Space Complexity? - -Space complexity is calculated by counting the amount of memory space used by the algorithm. It is calculated by counting the amount of memory space used by the algorithm as a function of the size of the input to the problem. - -## Example - -```js title="Space Complexity" -function sumOfN(n) { - let sum = 0; - for (let i = 1; i <= n; i++) { - sum += i; - } - return sum; -} -``` - -In the above example, the space complexity of the algorithm is O(1) because the algorithm uses a constant amount of memory space. - -## Example of Space Complexity - -1. Write a program to fine maximum and minimum element in an array. - - - - - ```js {6,9,12} - function findMaxMin(arr) { - let max = arr[0]; - let min = arr[0]; - for (let i = 1; i < arr.length; i++) { - if (arr[i] > max) { - max = arr[i]; - } - if (arr[i] < min) { - min = arr[i]; - } - } - return { max, min }; - } - - const arr = [2, 5, 1, 20, 10]; - console.log(findMaxMin(arr)); // { max: 20, min: 1 } - ``` - - - - - ```java - public class Main { - public static void main(String[] args) { - int[] arr = {2, 5, 1, 20, 10}; - System.out.println(findMaxMin(arr)); // { max: 20, min: 1 } - } - - public static Map findMaxMin(int[] arr) { - int max = arr[0]; - int min = arr[0]; - for (int i = 1; i < arr.length; i++) { - if (arr[i] > max) { - max = arr[i]; - } - if (arr[i] < min) { - min = arr[i]; - } - } - Map result = new HashMap<>(); - result.put("max", max); - result.put("min", min); - return result; - } - } - ``` - - - - - ```python - def find_max_min(arr): - max = arr[0] - min = arr[0] - for i in range(1, len(arr)): - if arr[i] > max: - max = arr[i] - if arr[i] < min: - min = arr[i] - return {"max": max, "min": min} - - arr = [2, 5, 1, 20, 10] - print(find_max_min(arr)) # { max: 20, min: 1 } - ``` - - - - - ```c - #include - - struct MaxMin { - int max; - int min; - }; - - struct MaxMin findMaxMin(int arr[], int n) { - struct MaxMin result; - result.max = arr[0]; - result.min = arr[0]; - for (int i = 1; i < n; i++) { - if (arr[i] > result.max) { - result.max = arr[i]; - } - if (arr[i] < result.min) { - result.min = arr[i]; - } - } - return result; - } - - int main() { - int arr[] = {2, 5, 1, 20, 10}; - struct MaxMin result = findMaxMin(arr, 5); - printf("{ max: %d, min: %d }\n", result.max, result.min); // { max: 20, min: 1 } - return 0; - } - ``` - - - - - ```cpp - #include - #include - #include - - std::map findMaxMin(std::vector arr) { - int max = arr[0]; - int min = arr[0]; - for (int i = 1; i < arr.size(); i++) { - if (arr[i] > max) { - max = arr[i]; - } - if (arr[i] < min) { - min = arr[i]; - } - } - std::map result; - result["max"] = max; - result["min"] = min; - return result; - } - - int main() { - std::vector arr = {2, 5, 1, 20, 10}; - std::map result = findMaxMin(arr); - std::cout << "{ max: " << result["max"] << ", min: " << result["min"] << " }\n"; // { max: 20, min: 1 } - return 0; - } - ``` - - - - -In the above example, the space complexity of the algorithm is O(1) because the algorithm uses a constant amount of memory space. - -**Explanation:** In the above example, we are finding the maximum and minimum element in an array. We are using two variables `max` and `min` to store the maximum and minimum element in the array. We are using a constant amount of memory space to store the maximum and minimum element in the array. Therefore, the space complexity of the algorithm is O(1). - -:::info Complexity Analysis -**Farmula to calculate Space Complexity** - -Space Complexity = Constant Space + Auxiliary Space - -**Constant Space:** The amount of space used by the algorithm that is not dependent on the size of the input to the problem. It is a constant amount of memory space used by the algorithm. - -**Auxiliary Space:** The amount of space used by the algorithm that is dependent on the size of the input to the problem. It is a variable amount of memory space used by the algorithm. - -```plaintext title="Space Complexity" -Space Complexity = O(1) + O(n) = O(n) -``` - -**For Example:** - -```js title="Space Complexity" -function sumOfN(n) { - let sum = 0; // Constant Space (O(1)) - for (let i = 1; i <= n; i++) { - sum += i; // Auxiliary Space (O(n)) - } - return sum; -} -``` - -In the above example, the space complexity of the algorithm is `O(1) + O(n) = O(n)`. - -::: - -## Conclusion - -Space complexity is a measure of the amount of working storage an algorithm needs. It is a measure of the amount of memory space an algorithm needs to solve a problem as a function of the size of the input to the problem. It is the amount of memory space required by the algorithm to execute in its life cycle. \ No newline at end of file diff --git a/docs/dsa/basic-concepts/time-complexity.md b/docs/dsa/basic-concepts/time-complexity.md deleted file mode 100644 index eb10b2909..000000000 --- a/docs/dsa/basic-concepts/time-complexity.md +++ /dev/null @@ -1,306 +0,0 @@ ---- -id: time-complexity -title: Time Complexity -sidebar_label: Time Complexity -sidebar_position: 1 -description: "Time Complexity is a measure of the amount of time an algorithm takes to solve a problem as a function of the size of the input to the problem. It is commonly estimated by counting the number of elementary operations performed by the algorithm, where an elementary operation takes a fixed amount of time to perform." -tags: [time complexity, big o notation, algorithm, complexity analysis, data structure, dsa, javascript, java, python, c, c++, time complexity example, time complexity calculation, time complexity analysis, time complexity explanation, time complexity conclusion, time complexity importance, time complexity formula, time complexity constant time, time complexity linear time, time complexity logarithmic time, time complexity quadratic time, time complexity exponential time, time complexity factorial time, time complexity polynomial time, time complexity sublinear time, time complexity linearithmic time, time complexity quasilinear time, time complexity superpolynomial time, time complexity subexponential time, time complexity log factorial time, time complexity exponential factorial time, time complexity exponential exponential time, time complexity exponential factorial exponential time, time complexity exponential exponential factorial time] ---- - -Time Complexity is a measure of the amount of time an algorithm takes to solve a problem as a function of the size of the input to the problem. It is commonly estimated by counting the number of elementary operations performed by the algorithm, where an elementary operation takes a fixed amount of time to perform. - -## Why is Time Complexity Important? - -Time Complexity is important because it helps us understand the efficiency of an algorithm. It allows us to compare different algorithms and choose the most efficient one for a given problem. It also helps us analyze the performance of an algorithm as the size of the input grows. - -## Common Notations for Time Complexity - -The most common notations used to represent the time complexity of an algorithm are: - -- **Big O Notation (O):** It represents the upper bound of the time complexity of an algorithm. It gives the worst-case time complexity of an algorithm. -- **Omega Notation (Ω):** It represents the lower bound of the time complexity of an algorithm. It gives the best-case time complexity of an algorithm. -- **Theta Notation (Θ):** It represents the average-case time complexity of an algorithm. It gives the tight bound of the time complexity of an algorithm. - -### Big O Notation (O) - -Big O Notation is used to represent the upper bound of the time complexity of an algorithm. It gives the worst-case time complexity of an algorithm. It is commonly used to analyze the performance of an algorithm as the size of the input grows. - -![Big O Notation](image.png) - -The Big O Notation is written as `O(f(n))`, where `f(n)` is a function that represents the time complexity of the algorithm. It is read as "O of f of n" or "order of f of n". - -### Omega Notation (Ω) - -Omega Notation is used to represent the lower bound of the time complexity of an algorithm. It gives the best-case time complexity of an algorithm. It is commonly used to analyze the performance of an algorithm as the size of the input grows. - -![Omega Notation](image-1.png) - -The Omega Notation is written as `Ω(f(n))`, where `f(n)` is a function that represents the time complexity of the algorithm. It is read as "Omega of f of n". - -### Theta Notation (Θ) - -Theta Notation is used to represent the average-case time complexity of an algorithm. It gives the tight bound of the time complexity of an algorithm. It is commonly used to analyze the performance of an algorithm as the size of the input grows. - -The Theta Notation is written as `Θ(f(n))`, where `f(n)` is a function that represents the time complexity of the algorithm. It is read as "Theta of f of n". - - -## Examples of Time Complexity - -Here are some examples of time complexity for different algorithms: - -- **Constant Time (O(1)):** An algorithm that takes the same amount of time to run, regardless of the size of the input. -- **Linear Time (O(n)):** An algorithm that takes time proportional to the size of the input. -- **Logarithmic Time (O(log n)):** An algorithm that takes time proportional to the logarithm of the size of the input. -- **Quadratic Time (O(n^2)):** An algorithm that takes time proportional to the square of the size of the input. -- **Exponential Time (O(2^n)):** An algorithm that takes time proportional to an exponential function of the size of the input. -- **Factorial Time (O(n!)):** An algorithm that takes time proportional to the factorial of the size of the input. -- **Polynomial Time (O(n^k)):** An algorithm that takes time proportional to a polynomial function of the size of the input. -- **Sublinear Time (O(log log n)):** An algorithm that takes time proportional to the logarithm of the logarithm of the size of the input. -- **Linearithmic Time (O(n log n)):** An algorithm that takes time proportional to the product of the size of the input and the logarithm of the size of the input. -- **Quasilinear Time (O(n log^k n)):** An algorithm that takes time proportional to the product of the size of the input and the logarithm of the size of the input raised to the power of k. -- **Superpolynomial Time (O(n^k)):** An algorithm that takes time proportional to a function that grows faster than any polynomial function of the size of the input. -- **Subexponential Time (O(2^poly(n))):** An algorithm that takes time proportional to a function that grows slower than any exponential function of the size of the input. -- **Log Factorial Time (O(log n!)):** An algorithm that takes time proportional to the logarithm of the factorial of the size of the input. -- **Exponential Factorial Time (O(2^n!)):** An algorithm that takes time proportional to an exponential function of the factorial of the size of the input. -- **Exponential Exponential Time (O(2^2^n)):** An algorithm that takes time proportional to an exponential function of an exponential function of the size of the input. -- **Exponential Factorial Exponential Time (O(2^n!^2^n)):** An algorithm that takes time proportional to an exponential function of the factorial of an exponential function of the size of the input. -- **Exponential Exponential Factorial Time (O(2^2^n!)):** An algorithm that takes time proportional to an exponential function of an exponential function of the factorial of the size of the input. - -## Analyzing Time Complexity - -To analyze the time complexity of an algorithm, we can follow these steps: - -1. **Count the Operations:** Count the number of elementary operations performed by the algorithm. -2. **Identify the Dominant Term:** Identify the term that grows the fastest as the size of the input grows. -3. **Express the Time Complexity:** Express the time complexity using the Big O notation. -4. **Compare with Other Algorithms:** Compare the time complexity with other algorithms to choose the most efficient one. -5. **Analyze the Best, Worst, and Average Cases:** Analyze the best-case, worst-case, and average-case time complexity of the algorithm. -6. **Optimize the Algorithm:** Optimize the algorithm to improve its time complexity if possible. -7. **Test the Algorithm:** Test the algorithm with different input sizes to verify its time complexity. -8. **Benchmark the Algorithm:** Benchmark the algorithm to measure its actual performance. -9. **Profile the Algorithm:** Profile the algorithm to identify performance bottlenecks and optimize them. -10. **Analyze the Real-World Performance:** Analyze the real-world performance of the algorithm in different environments and scenarios. -11. **Contribute:** If you have any tips to share, feel free to contribute to this section. - -## For Example - -1. Calculating sum of array elements using loop. - - - - - ```js - function sum(arr) { - let result = 0; - for (let i = 0; i < arr.length; i++) { - result += arr[i]; - } - return result; - } - const arr = [1, 2, 3, 4, 5]; - console.log(sum(arr)); // Output: 15 - ``` - - - ```py - def sum(arr): - result = 0 - for i in arr: - result += i - return result - arr = [1, 2, 3, 4, 5] - print(sum(arr)) # Output: 15 - ``` - - - ```java - class Sum { - public static void main(String args[]) { - int arr[] = {1, 2, 3, 4, 5}; - int result = 0; - for (int i = 0; i < arr.length; i++) { - result += arr[i]; - } - System.out.println(result); // Output: 15 - } - } - ``` - - - ```c - #include - int main() { - int arr[] = {1, 2, 3, 4, 5}; - int result = 0; - for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { - result += arr[i]; - } - printf("%d\n", result); // Output: 15 - return 0; - } - ``` - - - ```go - package main - import "fmt" - func main() { - arr := []int{1, 2, 3, 4, 5} - result := 0 - for i := 0; i < len(arr); i++ { - result += arr[i] - } - fmt.Println(result) // Output: 15 - } - ``` - - - ```cpp - #include - using namespace std; - int main() { - int arr[] = {1, 2, 3, 4, 5}; - int result = 0; - for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { - result += arr[i]; - } - cout << result << endl; // Output: 15 - return 0; - } - ``` - - - ```swift - import Foundation - let arr = [1, 2, 3, 4, 5] - var result = 0 - for i in arr { - result += i - } - print(result) // Output: 15 - ``` - - - ```kotlin - fun main() { - val arr = intArrayOf(1, 2, 3, 4, 5) - var result = 0 - for (i in arr) { - result += i - } - println(result) // Output: 15 - } - ``` - - - ```rs - fn main() { - let arr = [1, 2, 3, 4, 5]; - let mut result = 0; - for i in arr.iter() { - result += i; - } - println!("{}", result); // Output: 15 - } - ``` - - - ```php - - ``` - - - ```cs - using System; - class Sum { - static void Main() { - int[] arr = {1, 2, 3, 4, 5}; - int result = 0; - foreach (int i in arr) { - result += i; - } - Console.WriteLine(result); // Output: 15 - } - } - ``` - - - ```ts - let arr: number[] = [1, 2, 3, 4, 5]; - let result: number = 0; - for (let i of arr) { - result += i; - } - console.log(result); // Output: 15 - ``` - - - ```scala - object Sum { - def main(args: Array[String]): Unit = { - val arr = Array(1, 2, 3, 4, 5) - var result = 0 - for (i <- arr) { - result += i - } - println(result) // Output: 15 - } - } - ``` - - - ```haskell - main = do - let arr = [1, 2, 3, 4, 5] - let result = sum arr - print result -- Output: 15 - ``` - - - ```r - arr <- c(1, 2, 3, 4, 5) - result <- sum(arr) - print(result) # Output: 15 - ``` - - - ```perl - my @arr = (1, 2, 3, 4, 5); - my $result = 0; - foreach my $i (@arr) { - $result += $i; - } - print $result; # Output: 15 - ``` - - - ```lua - arr = {1, 2, 3, 4, 5} - result = 0 - for i = 1, #arr do - result = result + arr[i] - end - print(result) -- Output: 15 - ``` - - - -Each of the above code snippets has a time complexity of `O(n)` because the number of iterations in the loop is directly proportional to the size of the input array. - -**Exlpanation:** The time complexity of the given code is `O(n)` because the loop iterates through the array elements one by one, and the number of iterations is directly proportional to the size of the input array. Therefore, the time complexity is linear, i.e., `O(n)`. - - -:::info -**Note:** The time complexity of an algorithm can be different for different programming languages, but the underlying logic and analysis remain the same. -::: - -## Conclusion - -Time Complexity is an important concept in computer science and programming. It helps us understand the efficiency of algorithms and make informed decisions about choosing the most efficient algorithm for a given problem. By analyzing the time complexity of algorithms, we can optimize them for better performance and improve the overall efficiency of our programs. \ No newline at end of file diff --git a/docs/dsa/binary_search/Iterative_binary_search.md b/docs/dsa/binary_search/Iterative_binary_search.md deleted file mode 100644 index 7fab7b613..000000000 --- a/docs/dsa/binary_search/Iterative_binary_search.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -id: iterative-binary-search-DSA -title: Iterative Binary Search -sidebar_label: Iterative Binary Search -sidebar_position: 7 -description: "In this blog post, we'll explore the iterative binary search algorithm, a fundamental technique in computer science for efficiently finding an element in a sorted array. You'll learn what iterative binary search is, how it works, and its time complexity. We'll also cover practical applications and common problems you can solve using this algorithm. By the end, you'll have a thorough understanding of iterative binary search and how to implement it in your programming projects." -tags: [dsa, algorithms, binary search, iterative] ---- - -Iterative Binary Search is powerful algorithm that is essential for efficiently finding elements in sorted arrays, making it a staple in the toolkit of any adept programmer. Whether you're optimizing search operations or solving complex algorithmic challenges, understanding iterative binary search is crucial. Let's delve into its mechanics, applications, and implementation. - -## What is Iterative Binary Search? - -Iterative binary search is a highly efficient algorithm used to find an element in a sorted array. It works by repeatedly dividing the search interval in half, using an iterative approach. If the value of the search key is less than the item in the middle of the interval, the algorithm narrows the interval to the lower half. Otherwise, it narrows it to the upper half. The process continues until the search key is found or the interval is empty. - -In pseudo-code, iterative binary search is defined as follows: - -```cpp -FUNCTION iterativeBinarySearch(array, key): -low = 0 -high = array.length - 1 -WHILE low <= high: -mid = (low + high) / 2 -IF array[mid] == key: -RETURN mid -ELSE IF array[mid] < key: -low = mid + 1 -ELSE: -high = mid - 1 -RETURN -1 -``` - -```cpp -int iterativeBinarySearch(int array[], int size, int key) { - int low = 0; - int high = size - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (array[mid] == key) { - return mid; - } else if (array[mid] < key) { - low = mid + 1; - } else { - high = mid - 1; - } - } - return -1; -} -``` - -## How Iterative Binary Search Works - -### Step-by-Step Explanation - -1. Initialize: Set two pointers, low at the beginning and high at the end of the array. -2. Middle Element: Calculate the middle element's index. -Comparison: -3. If the middle element is the target, return its index. -4. If the middle element is less than the target, discard the left half by setting low to mid + 1. -5. If the middle element is greater than the target, discard the right half by setting high to mid - 1. -6. Repeat: Repeat steps 2 and 3 until the target is found or the low pointer exceeds the high pointer. - -### Time Complexity - -The time complexity of iterative binary search is $O(logn)$, -where $𝑛$ is the number of elements in the array. This logarithmic time complexity makes iterative binary search significantly faster than linear search for large datasets. - -## Practical Applications - -Iterative binary search is widely used in various real-world applications and algorithmic problems: - -1. Searching in a Sorted Array - The primary use of iterative binary search is to find elements in a sorted array efficiently. It is the foundation for more complex search algorithms. - -2. Dictionary Lookups - Iterative binary search is used in dictionaries (like the one you're reading now) to quickly find words and their definitions. - -3. Binary Search Trees - Iterative binary search is the basis for searching in binary search trees (BSTs), a fundamental data structure in computer science. - -4. Finding Boundaries - Iterative binary search can be adapted to find the first or last occurrence of a target element, making it useful in problems requiring boundary searches. - -Common Problems Solved Using Iterative Binary Search -Iterative binary search can be adapted in various ways to solve different types of problems. Here are a couple of common problems: - -1. Lower Bound and Upper Bound - These variations of iterative binary search are used to find the first and last occurrence of a target element in a sorted array. - -Lower Bound Pseudo-Code: - -```cpp -FUNCTION lowerBound(array, key): - low = 0 - high = array.length - WHILE low < high: - mid = (low + high) / 2 - IF array[mid] < key: - low = mid + 1 - ELSE: - high = mid - RETURN low - -``` - -Upper Bound Pseudo-Code: - -```cpp -FUNCTION upperBound(array, key): - low = 0 - high = array.length - WHILE low < high: - mid = (low + high) / 2 - IF array[mid] <= key: - low = mid + 1 - ELSE: - high = mid - RETURN low - - -``` - -2. Rotated Sorted Array - Iterative binary search can be modified to handle rotated sorted arrays, where the array is sorted but then rotated at some pivot point. - -:::tip -Handle Edge Cases: Ensure your implementation correctly handles cases where the target element is not present or when the array is empty. -Prevent Overflow: When calculating the middle index, use $\text{mid} = \text{low} + \frac{\text{high} - \text{low}}{2}$ instead of $\text{mid} = \frac{\text{low} + \text{high}}{2}$ to prevent potential overflow. -Efficiency: The iterative approach often uses less memory than the recursive approach because it doesn't involve the overhead of multiple recursive function calls. -::: - -## Conclusion - -Iterative binary search is a fundamental algorithm that every programmer should master. Its efficiency and versatility make it a powerful tool for solving a wide range of problems. By understanding how iterative binary search works and how to implement its variations, you'll be well-equipped to tackle numerous challenges in your programming journey. diff --git a/docs/dsa/binary_search/_category_.json b/docs/dsa/binary_search/_category_.json deleted file mode 100644 index 34c97b96a..000000000 --- a/docs/dsa/binary_search/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Binary Search", - "position": 7, - "link": { - "type": "generated-index", - "description": "Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). " - } -} diff --git a/docs/dsa/binary_search/binary-search.md b/docs/dsa/binary_search/binary-search.md deleted file mode 100644 index fbc27804e..000000000 --- a/docs/dsa/binary_search/binary-search.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -id: binary-search-dsa -title: Binary Search -sidebar_label: Binary Search -description: "In this blog post, we'll dive into the binary search algorithm, a fundamental technique in computer science for efficiently finding an element in a sorted array." -tags: [dsa, algorithms, binary search] ---- - - -## Introduction -Binary search is a searching algorithm, used to search for an element in an array. It follows a unique approach which reduces the time complexity as compared to linear search. However, to use binary search, the array must be sorted. - -## Implementation - -Let us see how to implement binary search in Java: - -```java - //let element to be found=target - int low=0; - int high=n-1; //where n is the length of the sorted array - int mid; //represents the mid index of the array - - int flag=0; //element not yet found - - while(low<=high) { - - mid=(low + high)/2; - if(arr[mid]==target) { - flag=1; //element found - System.out.println("Target found!"); - break; - } - else if(arr[mid] -Binary search : O(log n) - -## Points to Remember: - -- Binary search requires a sorted array. -- Works for 1 dimensional arrays. -- Faster and complex than sequential search. -- Uses the divide and conquer approach. -- Best if arrays are too long (large datasets). diff --git a/docs/dsa/binary_search/recursive_binary_search.md b/docs/dsa/binary_search/recursive_binary_search.md deleted file mode 100644 index 4d3c50f27..000000000 --- a/docs/dsa/binary_search/recursive_binary_search.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -id: recursive-binary-search-DSA -title: Recursive Binary Search -sidebar_label: Recursive Binary Search -sidebar_position: 8 -description: "In this blog post, we'll explore the recursive binary search algorithm, a fundamental technique in computer science for efficiently finding an element in a sorted array. You'll learn what recursive binary search is, how it works, and its time complexity. We'll also cover practical applications and common problems you can solve using this algorithm. By the end, you'll have a thorough understanding of recursive binary search and how to implement it in your programming projects." -tags: [dsa, algorithms, binary search, recursive] ---- - -Recursive Binary Search algorithm is essential for efficiently finding elements in sorted arrays, making it a staple in the toolkit of any adept programmer. Whether you're optimizing search operations or solving complex algorithmic challenges, understanding recursive binary search is crucial. Let's delve into its mechanics, applications, and implementation. - -## What is Recursive Binary Search? - -Recursive binary search is a highly efficient algorithm used to find an element in a sorted array. It works by repeatedly dividing the search interval in half, using a recursive approach. If the value of the search key is less than the item in the middle of the interval, the algorithm narrows the interval to the lower half. Otherwise, it narrows it to the upper half. The process continues until the search key is found or the interval is empty. - -In pseudo-code, recursive binary search is defined as follows: - -```cpp -FUNCTION recursiveBinarySearch(array, low, high, key): -IF low > high: -RETURN -1 -mid = (low + high) / 2 -IF array[mid] == key: -RETURN mid -ELSE IF array[mid] < key: -RETURN recursiveBinarySearch(array, mid + 1, high, key) -ELSE: -RETURN recursiveBinarySearch(array, low, mid - 1, key) -``` - -```cpp -int recursiveBinarySearch(int array[], int low, int high, int key) { - if (low > high) { - return -1; - } - int mid = low + (high - low) / 2; - if (array[mid] == key) { - return mid; - } else if (array[mid] < key) { - return recursiveBinarySearch(array, mid + 1, high, key); - } else { - return recursiveBinarySearch(array, low, mid - 1, key); - } -} -``` - -## How Recursive Binary Search Works - -### Step-by-Step Explanation - -1. Initialize: Set two pointers, low at the beginning and high at the end of the array. -2. Middle Element: Calculate the middle element's index. -Comparison: -3. If the middle element is the target, return its index. -4. If the middle element is less than the target, discard the left half by setting low to mid + 1. -5. If the middle element is greater than the target, discard the right half by setting high to mid - 1. -6. Repeat: Repeat steps 2 and 3 until the target is found or the low pointer exceeds the high pointer. - -### Time Complexity - -The time complexity of iterative binary search is $𝑂(log𝑛)$. - -where $n$ is the number of elements in the array. This logarithmic time complexity makes iterative binary search significantly faster than linear search for large datasets. - -## Practical Applications - -Iterative binary search is widely used in various real-world applications and algorithmic problems: - -1. Searching in a Sorted Array - The primary use of iterative binary search is to find elements in a sorted array efficiently. It is the foundation for more complex search algorithms. - -2. Dictionary Lookups - Iterative binary search is used in dictionaries (like the one you're reading now) to quickly find words and their definitions. - -3. Binary Search Trees - Iterative binary search is the basis for searching in binary search trees (BSTs), a fundamental data structure in computer science. - -4. Finding Boundaries - Iterative binary search can be adapted to find the first or last occurrence of a target element, making it useful in problems requiring boundary searches. - -Common Problems Solved Using Iterative Binary Search -Iterative binary search can be adapted in various ways to solve different types of problems. Here are a couple of common problems: - -1. Lower Bound and Upper Bound - These variations of iterative binary search are used to find the first and last occurrence of a target element in a sorted array. - -Lower Bound Pseudo-Code: - -```cpp -FUNCTION lowerBound(array, low, high, key): - IF low == high: - RETURN low - mid = (low + high) / 2 - IF array[mid] < key: - RETURN lowerBound(array, mid + 1, high, key) - ELSE: - RETURN lowerBound(array, low, mid, key) - - -``` - -Upper Bound Pseudo-Code: - -```cpp -FUNCTION upperBound(array, low, high, key): - if low == high: - return low - mid = (low + high) / 2 - if array[mid] <= key: - return upperBound(array, mid + 1, high, key) - else: - return upperBound(array, low, mid, key) - -``` - -2. Rotated Sorted Array - Recursive binary search can be modified to handle rotated sorted arrays, where the array is sorted but then rotated at some pivot point. - -:::tip -Handle Edge Cases: Ensure your implementation correctly handles cases where the target element is not present or when the array is empty. -Prevent Stack Overflow: Be mindful of the recursion depth, especially for large arrays, as deep recursion can lead to stack overflow. -Efficiency: The recursive approach can be more intuitive and elegant, but consider the iterative approach for environments with limited stack size. -::: - -## Conclusion -Recursive binary search is a fundamental algorithm that every programmer should master. Its efficiency and versatility make it a powerful tool for solving a wide range of problems. By understanding how recursive binary search works and how to implement its variations, you'll be well-equipped to tackle numerous challenges in your programming journey. diff --git a/docs/dsa/data-structure-types.md b/docs/dsa/data-structure-types.md deleted file mode 100644 index 350d26e72..000000000 --- a/docs/dsa/data-structure-types.md +++ /dev/null @@ -1,367 +0,0 @@ ---- -id: data-structure-types -title: Data Structure Types -sidebar_label: Data Structure Types -sidebar_position: 2 -description: "Data structures are used to represent data in a meaningful way. They provide a way to store and organize data in memory. This section covers the different types of data structures and their applications." -tags: - [ - dsa, - data-structures, - types, - data structure types, - primitive data types, - abstract data types, - linear data structures, - non-linear data structures, - homogeneous data structures, - heterogeneous data structures, - static data structures, - dynamic data structures, - mutable data structures, - immutable data structures, - persistent data structures, - transient data structures, - stack, - queue, - linked list, - tree, - graph, - hash table, - set, - map, - dictionary, - priority queue, - heap, - trie, - bloom filter, - bit array, - bitset, - bitboard, - ] ---- - -A data structure is a way of organizing and storing data so that it can be accessed and modified efficiently. It is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data. Data structures are used to represent data in a meaningful way. They provide a way to store and organize data in memory. - -Data structures can be classified into different types based on various criteria. Here are some common types of data structures: - -```mermaid -graph TD - A[Data Structures] --> B[Primitive Data Structures] - A[Data Structures] --> C[Non-Primitive Data Structures] - - B[Primitive Data Structures] --> D(Integer) - B[Primitive Data Structures] --> E(Float) - B[Primitive Data Structures] --> F(Character) - B[Primitive Data Structures] --> G(Boolean) - - C[Non-Primitive Data Structures] --> H[Linear Data Structures] - C[Non-Primitive Data Structures] --> I[Non-Linear Data Structures] - - H[Linear Data Structures] --> J[Static Data Structures] - H[Linear Data Structures] --> K[Dynamic Data Structures] - - J[Static Data Structures] --> L(Array) - - K[Dynamic Data Structures] --> M(Linked List) - K[Dynamic Data Structures] --> N(Stack) - K[Dynamic Data Structures] --> O(Queue) - - I[Non-Linear Data Structures] --> P[Trees] - I[Non-Linear Data Structures] --> Q[Graphs] -``` - -### Primitive Data Structures - -Primitive data structures are the basic data structures that are directly operated upon by the machine instructions. They include: - -1. **Integer**: A data type that represents whole numbers. - - for example: `1`, `2`, `3`, `4`, `5`, ... - - ```javascript title="Integer" - let num = 10; - ``` - -2. **Float**: A data type that represents real numbers with decimal points. - - for example: `1.0`, `2.5`, `3.14`, `4.2`, `5.75`, ... - - ```javascript title="Float" - let num = 3.14; - ``` - -3. **Character**: A data type that represents a single character. - - for example: `a`, `b`, `c`, `d`, `e`, ... - - ```javascript title="Character" - let ch = "A"; - ``` - -4. **Boolean**: A data type that represents true or false values. - - for example: `true`, `false` - - ```javascript title="Boolean" - let isTrue = true; - ``` - -### Non-Primitive Data Structures - -Non-primitive data structures are the advanced data structures that are derived from primitive data structures. They include: - -1. **Linear Data Structures**: Data structures in which elements are arranged in a sequential manner. They include: - - - **Static Data Structures**: Data structures in which the size is fixed at compile time. They include: - - - **Array**: A collection of elements of the same data type stored in contiguous memory locations. - - ```javascript title="Array" - let arr = [1, 2, 3, 4, 5]; - ``` - - - **Dynamic Data Structures**: Data structures in which the size can be changed at runtime. They include: - - - **Linked List**: A collection of elements called nodes, where each node contains a data field and a reference (link) to the next node in the sequence. - - ```javascript title="Linked List" - class Node { - constructor(data) { - this.data = data; - this.next = null; - } - } - - class LinkedList { - constructor() { - this.head = null; - } - - add(data) { - const newNode = new Node(data); - - if (!this.head) { - this.head = newNode; - } else { - let current = this.head; - - while (current.next) { - current = current.next; - } - - current.next = newNode; - } - } - } - - const list = new LinkedList(); - list.add(1); - list.add(2); - list.add(3); - ``` - - - **Stack**: A collection of elements with two main operations: push (insert) and pop (delete). - - ```javascript title="Stack" - class Stack { - constructor() { - this.items = []; - } - - push(element) { - this.items.push(element); - } - - pop() { - if (this.items.length === 0) { - return "Underflow"; - } - return this.items.pop(); - } - } - - const stack = new Stack(); - stack.push(1); - stack.push(2); - stack.push(3); - stack.pop(); - ``` - - - **Queue**: A collection of elements with two main operations: enqueue (insert) and dequeue (delete). - - ```javascript title="Queue" - class Queue { - constructor() { - this.items = []; - } - - enqueue(element) { - this.items.push(element); - } - - dequeue() { - if (this.items.length === 0) { - return "Underflow"; - } - return this.items.shift(); - } - } - - const queue = new Queue(); - queue.enqueue(1); - queue.enqueue(2); - queue.enqueue(3); - queue.dequeue(); - ``` - -2. **Non-Linear Data Structures**: Data structures in which elements are not arranged in a sequential manner. They include: - - - **Trees**: A hierarchical data structure with a root node and subtrees of children nodes. - - ```javascript title="Tree" - class Node { - constructor(data) { - this.data = data; - this.children = []; - } - - addChild(data) { - const child = new Node(data); - this.children.push(child); - } - } - - const tree = new Node(1); - tree.addChild(2); - tree.addChild(3); - ``` - - - **Graphs**: A non-linear data structure consisting of nodes (vertices) and edges (connections between nodes). - - ```javascript title="Graph" - class Graph { - constructor() { - this.nodes = []; - this.edges = []; - } - - addNode(node) { - this.nodes.push(node); - } - - addEdge(node1, node2) { - this.edges.push([node1, node2]); - } - } - - const graph = new Graph(); - graph.addNode(1); - graph.addNode(2); - graph.addEdge(1, 2); - ``` - - - **Hash Table**: A data structure that stores key-value pairs and provides fast lookup of values based on keys. - - ```javascript title="Hash Table" - class HashTable { - constructor() { - this.table = {}; - } - - put(key, value) { - this.table[key] = value; - } - - get(key) { - return this.table[key]; - } - } - - const hashTable = new HashTable(); - hashTable.put("name", "John"); - hashTable.get("name"); - ``` - - - **Heap**: A specialized tree-based data structure that satisfies the heap property. - - ```javascript title="Heap" - class MinHeap { - constructor() { - this.heap = []; - } - - insert(value) { - this.heap.push(value); - this.heapifyUp(); - } - - heapifyUp() { - let index = this.heap.length - 1; - - while (index > 0) { - let parentIndex = Math.floor((index - 1) / 2); - - if (this.heap[parentIndex] <= this.heap[index]) { - break; - } - - [this.heap[parentIndex], this.heap[index]] = [ - this.heap[index], - this.heap[parentIndex], - ]; - index = parentIndex; - } - } - } - - const minHeap = new MinHeap(); - minHeap.insert(3); - minHeap.insert(2); - minHeap.insert(1); - ``` - -## Different Between Primitive and Non-Primitive Data Structures - -|No. |Primitive Data Structures|Non-Primitive Data Structures| -|----|--------------------------|-----------------------------| -|1. |Basic data structures that are directly operated upon by the machine instructions.|Advanced data structures that are derived from primitive data structures.| -|2. |Examples: Integer, Float, Character, Boolean.|Examples: Array, Linked List, Stack, Queue, Tree, Graph, Hash Table, Heap.| -|3. |Stored in contiguous memory locations.|Stored in non-contiguous memory locations.| -|4. |Fixed size at compile time.|Size can be changed at runtime.| -|5. |Efficient for simple data storage and retrieval.|Efficient for complex data storage and retrieval.| -|6. |Low-level data structures.|High-level data structures.| - -## Different Between Linear and Non-Linear Data Structures - -|No. |Linear Data Structures|Non-Linear Data Structures| -|----|-----------------------|-------------------------| -|1. |Data structures in which elements are arranged in a sequential manner.|Data structures in which elements are not arranged in a sequential manner.| -|2. |Examples: Array, Linked List, Stack, Queue.|Examples: Tree, Graph.| -|3. |Elements are stored in a linear sequence.|Elements are stored in a non-linear sequence.| -|4. |Efficient for simple data storage and retrieval.|Efficient for complex data storage and retrieval.| -|5. |Low-level data structures.|High-level data structures.| - -## Different Between Static and Dynamic Data Structures - -|No. |Static Data Structures|Dynamic Data Structures| -|----|----------------------|----------------------| -|1. |Data structures in which the size is fixed at compile time.|Data structures in which the size can be changed at runtime.| -|2. |Examples: Array.|Examples: Linked List, Stack, Queue.| -|3. |Size is determined at compile time.|Size can be changed at runtime.| -|4. |Efficient for fixed-size data storage and retrieval.|Efficient for variable-size data storage and retrieval.| -|5. |Low-level data structures.|High-level data structures.| - -## Different Between Mutable and Immutable Data Structures - -|No. |Mutable Data Structures|Immutable Data Structures| -|----|-----------------------|------------------------| -|1. |Data structures in which the data can be modified after creation.|Data structures in which the data cannot be modified after creation.| -|2. |Examples: Array, Linked List, Stack, Queue.|Examples: String, Tuple, Set, Map.| -|3. |Data can be changed after creation.|Data cannot be changed after creation.| -|4. |Efficient for data that needs to be modified frequently.|Efficient for data that needs to be shared and reused.| -|5. |Low-level data structures.|High-level data structures.| - -## Conclusion - -Data structures are the building blocks of computer science. They are the tools you'll use to build software systems. Understanding the different types of data structures and their applications is essential for designing efficient algorithms and solving complex problems. By learning data structures, you'll be able to represent data in a meaningful way, store and organize data in memory, and build software systems that are scalable, efficient, and reliable. \ No newline at end of file diff --git a/docs/dsa/dsa.md b/docs/dsa/dsa.md deleted file mode 100644 index 4f0fdce3e..000000000 --- a/docs/dsa/dsa.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -id: dsa -title: Data Structures and Algorithms -sidebar_label: Data Structures and Algorithms -sidebar_position: 1 -description: "Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. This section is a collection of resources to help you understand and master Data Structures and Algorithms." -tags: [dsa, data-structures, algorithms, programming, computer-science, software-engineering, competitive-programming, interview-preparation, open-source, learning, teaching, problem-solving, performance, career-growth, understanding, competitive-programming, coding-competitions, open-source, building-systems, learning-new-technologies, programming-languages, tools, concepts, problem-solving, data-structures, algorithms, resources, books, websites, courses, youtube-channels, practice, interview-preparation, competitive-programming, community, contribute] ---- - -> Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. This section is a collection of resources to help you understand and master Data Structures and Algorithms. - -## Introduction - -Data Structures and Algorithms are the fundamental concepts that every programmer must know. They are the tools you'll use to build software systems. Data Structures are a way of organizing and storing data so that it can be accessed and modified efficiently. Algorithms are a set of instructions to solve a problem or perform a task. - -## What is Algorithm? - -An algorithm is a set of instructions to solve a problem or perform a task. It is a step-by-step procedure that defines a set of actions to be executed in a certain order to get the desired output. - -### Quility of Good Algorithm - -- **Correctness**: An algorithm is correct if it produces the correct result for all instances of the problem it is designed to solve. -- **Efficiency**: An algorithm is efficient if it solves the problem within the resources (like time and space) available to it. -- **Simplicity**: An algorithm is simple if it is easy to understand and implement. -- **Optimality**: An algorithm is optimal if it produces the best result among all possible solutions for the given problem. -- **Scalability**: An algorithm is scalable if it can handle the input size efficiently. -- **Adaptability**: An algorithm is adaptable if it can be easily modified to solve a different problem. -- **Robustness**: An algorithm is robust if it can handle invalid input without crashing. -- **Maintainability**: An algorithm is maintainable if it can be easily modified and maintained. -- **Reusability**: An algorithm is reusable if it can be used in different programs. - -### Algorithm Examples - -- **Sorting Algorithms**: Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort, Heap Sort, Radix Sort, Counting Sort, Bucket Sort, etc. -- **Searching Algorithms**: Linear Search, Binary Search, Jump Search, Interpolation Search, Exponential Search, etc. -- **Graph Algorithms**: Breadth-First Search (BFS), Depth-First Search (DFS), Dijkstra's Algorithm, Bellman-Ford Algorithm, Floyd-Warshall Algorithm, Prim's Algorithm, Kruskal's Algorithm, etc. -- **Dynamic Programming Algorithms**: Fibonacci Series, Longest Common Subsequence, Longest Increasing Subsequence, Knapsack Problem, Matrix Chain Multiplication, etc. -- **Greedy Algorithms**: Fractional Knapsack Problem, Job Sequencing Problem, Huffman Coding, Prim's Algorithm, Kruskal's Algorithm, etc. -- **Divide and Conquer Algorithms**: Binary Search, Merge Sort, Quick Sort, Strassen's Algorithm, etc. -- **Backtracking Algorithms**: N-Queens Problem, Sudoku Solver, Knight's Tour, Rat in a Maze, etc. -- **Branch and Bound Algorithms**: Traveling Salesman Problem, 0/1 Knapsack Problem, Job Assignment Problem, etc. -- **Randomized Algorithms**: Randomized Quick Sort, Randomized Selection, Las Vegas Algorithm, Monte Carlo Algorithm, etc. -- **Approximation Algorithms**: Traveling Salesman Problem, Knapsack Problem, Set Cover Problem, etc. - -## What is Data Structure? - -A data structure is a way of organizing and storing data so that it can be accessed and modified efficiently. It is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data. Data structures are used to represent data in a meaningful way. They provide a way to store and organize data in memory. - -![Data Structure](image.png) - -:::note -Data structures are the building blocks of computer science. They are the tools you'll use to build software systems. Data structures are used to represent data in a meaningful way. They provide a way to store and organize data in memory. -::: - -### Types of Data Structures - -Data structures can be classified into two categories: - -```mermaid -graph TD - A[Data Structures] --> B[Primative Data Structures] - A[Data Structures] --> C[Non-Primative Data Structures] - - B[Primative Data Structures] --> D(Integer) - B[Primative Data Structures] --> EFloat - B[Primative Data Structures] --> F(Character) - B[Primative Data Structures] --> G(Boolean) - - C[Non-Primative Data Structures] --> H[Linear Data Structures] - C[Non-Primative Data Structures] --> I[Non-Linear Data Structures] - - H[Linear Data Structures] --> J[Static Data Structures] - H[Linear Data Structures] --> K[Dynamic Data Structures] - - J[Static Data Structures] --> L(Array) - - K[Dynamic Data Structures] --> M(Linked List) - K[Dynamic Data Structures] --> N(Stack) - K[Dynamic Data Structures] --> O(Queue) - - I[Non-Linear Data Structures] --> Q(Trees) - I[Non-Linear Data Structures] --> R(Graphs) - -``` - -1. **Primitive Data Structures**: These are the basic data structures that are directly operated upon by the machine instructions. They include Integer, Float, Character, Boolean, etc. -2. **Non-Primitive Data Structures**: These are the advanced data structures that are derived from primitive data structures. They include Linear Data Structures (Array, Linked List, Stack, Queue), Non-Linear Data Structures (Trees, Graphs), etc. - -### Data Structure Examples - -- **Array**: A collection of elements of the same data type stored in contiguous memory locations. -- **Linked List**: A collection of elements called nodes, where each node contains a data field and a reference (link) to the next node in the sequence. -- **Stack**: A collection of elements with two main operations: push (insert) and pop (delete). -- **Queue**: A collection of elements with two main operations: enqueue (insert) and dequeue (delete). -- **Tree**: A hierarchical data structure with a root node and subtrees of children nodes. -- **Graph**: A non-linear data structure consisting of nodes (vertices) and edges (connections between nodes). -- **Hash Table**: A data structure that stores key-value pairs and provides fast lookup of values based on keys. -- **Heap**: A specialized tree-based data structure that satisfies the heap property. - -## Why Learn Data Structures and Algorithms? - -Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. Here are some reasons why you should learn Data Structures and Algorithms: - -1. **Problem Solving**: Data Structures and Algorithms help you solve complex problems efficiently. -2. **Performance**: Data Structures and Algorithms help you write efficient code that runs faster and uses less memory. -3. **Understanding**: Data Structures and Algorithms help you understand how software systems work under the hood. -4. **Career Growth**: Data Structures and Algorithms are essential skills for software engineers, data scientists, machine learning engineers, and other tech professionals. -5. **Interview Preparation**: Data Structures and Algorithms are commonly asked in technical interviews for software engineering roles. -6. **Competitive Programming**: Data Structures and Algorithms are essential for competitive programming and coding competitions. -7. **Open Source**: Data Structures and Algorithms are used in open-source projects and libraries. -8. **Learning New Technologies**: Data Structures and Algorithms help you learn new programming languages, tools, and concepts. -9. **Building Systems**: Data Structures and Algorithms are the foundation of building software systems. -10. **Community**: Data Structures and Algorithms have a vibrant community of learners, educators, and practitioners. - -## Resources - -Here are some resources to help you learn and master Data Structures and Algorithms: - -1. **Books**: Introduction to Algorithms, Data Structures and Algorithms in Python, Algorithms, The Algorithm Design Manual, etc. -2. **Websites**: GeeksforGeeks, LeetCode, HackerRank, CodeSignal, CodeChef, TopCoder, etc. -3. **Courses**: Coursera, edX, Udemy, Khan Academy, MIT OpenCourseWare, Stanford Online, etc. -4. **YouTube Channels**: freeCodeCamp, HackerRank, GeeksforGeeks, mycodeschool, Abdul Bari, etc. -5. **Practice**: LeetCode, HackerRank, GeeksforGeeks, CodeChef, TopCoder, etc. - -## Conclusion - -Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. This section is a collection of resources to help you understand and master Data Structures and Algorithms. Happy learning! \ No newline at end of file diff --git a/docs/dsa/graphs/_category_.json b/docs/dsa/graphs/_category_.json deleted file mode 100644 index 440450f74..000000000 --- a/docs/dsa/graphs/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Graphs", - "position": 14, - "link": { - "type": "generated-index", - "description": "Graphs are a data structure that represents a collection of interconnected nodes or vertices. They are commonly used in Data Structures and Algorithms (DSA) to model relationships between objects or entities." - } -} diff --git a/docs/dsa/graphs/graphs.md b/docs/dsa/graphs/graphs.md deleted file mode 100644 index a914f12e6..000000000 --- a/docs/dsa/graphs/graphs.md +++ /dev/null @@ -1,301 +0,0 @@ - - -# Graphs in Data Structures and Algorithms (DSA) - -Graphs in Data Structures and Algorithms (DSA) are a non-linear data structure that consists of a set of vertices (nodes) connected by edges. They are widely used to represent relationships between objects or entities. - -![alt text](image.png) - -## Implementing a Graph using an Adjacency Matrix - -To implement a graph, you can use various data structures such as an adjacency matrix or an adjacency list. - -An adjacency matrix is a 2D array where each cell represents the presence or absence of an edge between two vertices. It requires O(V^2) space, where V is the number of vertices. - -Here's an example of implementing a graph using an adjacency matrix in Python: - -```python -class Graph: - def __init__(self, num_vertices): - self.num_vertices = num_vertices - self.adj_matrix = [[0] * num_vertices for _ in range(num_vertices)] - - def add_edge(self, src, dest): - self.adj_matrix[src][dest] = 1 - self.adj_matrix[dest][src] = 1 - - def remove_edge(self, src, dest): - self.adj_matrix[src][dest] = 0 - self.adj_matrix[dest][src] = 0 - - def print_graph(self): - for row in self.adj_matrix: - print(row) - -# Example usage: -g = Graph(4) -g.add_edge(0, 1) -g.add_edge(1, 2) -g.add_edge(2, 3) -g.print_graph() -``` - -Output: -```plaintext -[0, 1, 0, 0] -[1, 0, 1, 0] -[0, 1, 0, 1] -[0, 0, 1, 0] -``` - -## Implementing a Graph using an Adjacency List - -Another way to implement a graph is using an adjacency list. It is a collection of linked lists, where each vertex has a list of its adjacent vertices. It requires O(V + E) space, where V is the number of vertices and E is the number of edges. - -Here's an example of implementing a graph using an adjacency list in Python: - -```python -class Graph: - def __init__(self, num_vertices): - self.num_vertices = num_vertices - self.adj_list = [[] for _ in range(num_vertices)] - - def add_edge(self, src, dest): - self.adj_list[src].append(dest) - self.adj_list[dest].append(src) - - def remove_edge(self, src, dest): - self.adj_list[src].remove(dest) - self.adj_list[dest].remove(src) - - def print_graph(self): - for vertex, adj_vertices in enumerate(self.adj_list): - print(f"Vertex {vertex}: {adj_vertices}") - -# Example usage: -g = Graph(4) -g.add_edge(0, 1) -g.add_edge(1, 2) -g.add_edge(2, 3) -g.print_graph() -``` - -Output: -```plaintext -Vertex 0: [1] -Vertex 1: [0, 2] -Vertex 2: [1, 3] -Vertex 3: [2] -``` - -## Additional Operations on Graphs - -These are just basic operations on graphs. Depending on your requirements, you can perform various other operations like finding a path between two vertices, checking for cycles, or finding the shortest path using algorithms like Depth-First Search (DFS) or Breadth-First Search (BFS). - - -Graphs in Data Structures and Algorithms (DSA) are a non-linear data structure that consists of a set of vertices (nodes) connected by edges. They are widely used to represent relationships between objects or entities. - -To implement a graph, you can use various data structures such as an adjacency matrix or an adjacency list. - -An adjacency matrix is a 2D array where each cell represents the presence or absence of an edge between two vertices. It requires O(V^2) space, where V is the number of vertices. - -Here's an example of implementing a graph using an adjacency matrix in Python: - -```python -class Graph: - def __init__(self, num_vertices): - self.num_vertices = num_vertices - self.adj_matrix = [[0] * num_vertices for _ in range(num_vertices)] - - def add_edge(self, src, dest): - self.adj_matrix[src][dest] = 1 - self.adj_matrix[dest][src] = 1 - - def remove_edge(self, src, dest): - self.adj_matrix[src][dest] = 0 - self.adj_matrix[dest][src] = 0 - - def print_graph(self): - for row in self.adj_matrix: - print(row) - -# Example usage: -g = Graph(4) -g.add_edge(0, 1) -g.add_edge(1, 2) -g.add_edge(2, 3) -g.print_graph() -``` - -Output: -``` -[0, 1, 0, 0] -[1, 0, 1, 0] -[0, 1, 0, 1] -[0, 0, 1, 0] -``` - -Another way to implement a graph is using an adjacency list. It is a collection of linked lists, where each vertex has a list of its adjacent vertices. It requires O(V + E) space, where V is the number of vertices and E is the number of edges. - -Here's an example of implementing a graph using an adjacency list in Python: - -```python -class Graph: - def __init__(self, num_vertices): - self.num_vertices = num_vertices - self.adj_list = [[] for _ in range(num_vertices)] - - def add_edge(self, src, dest): - self.adj_list[src].append(dest) - self.adj_list[dest].append(src) - - def remove_edge(self, src, dest): - self.adj_list[src].remove(dest) - self.adj_list[dest].remove(src) - - def print_graph(self): - for vertex, adj_vertices in enumerate(self.adj_list): - print(f"Vertex {vertex}: {adj_vertices}") - -# Example usage: -g = Graph(4) -g.add_edge(0, 1) -g.add_edge(1, 2) -g.add_edge(2, 3) -g.print_graph() -``` - -Output: -``` -Vertex 0: [1] -Vertex 1: [0, 2] -Vertex 2: [1, 3] -Vertex 3: [2] -``` - -These are just basic operations on graphs. Depending on your requirements, you can perform various other operations like finding a path between two vertices, checking for cycles, or finding the shortest path using algorithms like Depth-First Search (DFS) or Breadth-First Search (BFS). - -## Implementing a Graph in Java - -To implement a graph in Java, you can use similar approaches as in Python. Here's an example of implementing a graph using an adjacency matrix in Java: - -```java -public class Graph { - private int numVertices; - private int[][] adjMatrix; - - public Graph(int numVertices) { - this.numVertices = numVertices; - this.adjMatrix = new int[numVertices][numVertices]; - } - - public void addEdge(int src, int dest) { - adjMatrix[src][dest] = 1; - adjMatrix[dest][src] = 1; - } - - public void removeEdge(int src, int dest) { - adjMatrix[src][dest] = 0; - adjMatrix[dest][src] = 0; - } - - public void printGraph() { - for (int i = 0; i < numVertices; i++) { - for (int j = 0; j < numVertices; j++) { - System.out.print(adjMatrix[i][j] + " "); - } - System.out.println(); - } - } - - public static void main(String[] args) { - Graph g = new Graph(4); - g.addEdge(0, 1); - g.addEdge(1, 2); - g.addEdge(2, 3); - g.printGraph(); - } -} -``` - -Output: -``` -0 1 0 0 -1 0 1 0 -0 1 0 1 -0 0 1 0 -``` - -## Implementing a Graph in C++ - -Similarly, you can implement a graph in C++ using an adjacency matrix. Here's an example: - -```cpp -#include -#include - -using namespace std; - -class Graph { -private: - int numVertices; - vector> adjMatrix; - -public: - Graph(int numVertices) { - this->numVertices = numVertices; - this->adjMatrix.resize(numVertices, vector(numVertices, 0)); - } - - void addEdge(int src, int dest) { - adjMatrix[src][dest] = 1; - adjMatrix[dest][src] = 1; - } - - void removeEdge(int src, int dest) { - adjMatrix[src][dest] = 0; - adjMatrix[dest][src] = 0; - } - - void printGraph() { - for (int i = 0; i < numVertices; i++) { - for (int j = 0; j < numVertices; j++) { - cout << adjMatrix[i][j] << " "; - } - cout << endl; - } - } -}; - -int main() { - Graph g(4); - g.addEdge(0, 1); - g.addEdge(1, 2); - g.addEdge(2, 3); - g.printGraph(); - - return 0; -} -``` - -Output: -``` -0 1 0 0 -1 0 1 0 -0 1 0 1 -0 0 1 0 -``` - -Remember to adjust the number of vertices and edges according to your requirements. - -In conclusion, graphs are a fundamental data structure in Data Structures and Algorithms (DSA) that are used to represent relationships between objects or entities. They can be implemented using various data structures such as an adjacency matrix or an adjacency list. - -An adjacency matrix is a 2D array that represents the presence or absence of edges between vertices. It requires O(V^2) space, where V is the number of vertices. On the other hand, an adjacency list is a collection of linked lists where each vertex has a list of its adjacent vertices. It requires O(V + E) space, where V is the number of vertices and E is the number of edges. - -Both implementations have their own advantages and disadvantages. The choice of implementation depends on the specific requirements of the problem at hand. - -Additionally, there are various other operations that can be performed on graphs, such as finding a path between two vertices, checking for cycles, or finding the shortest path using algorithms like Depth-First Search (DFS) or Breadth-First Search (BFS). - -Graphs can also be implemented in other programming languages like Java and C++. The implementation follows similar approaches using either an adjacency matrix or an adjacency list. - -Overall, understanding graphs and their implementations is crucial for solving problems that involve relationships and connectivity between entities. diff --git a/docs/dsa/graphs/image.png b/docs/dsa/graphs/image.png deleted file mode 100644 index 6398c1d98..000000000 Binary files a/docs/dsa/graphs/image.png and /dev/null differ diff --git a/docs/dsa/image.png b/docs/dsa/image.png deleted file mode 100644 index 6fec02237..000000000 Binary files a/docs/dsa/image.png and /dev/null differ diff --git a/docs/dsa/linkedlist/LinkedList.md b/docs/dsa/linkedlist/LinkedList.md deleted file mode 100644 index e002a1880..000000000 --- a/docs/dsa/linkedlist/LinkedList.md +++ /dev/null @@ -1,695 +0,0 @@ ---- -id: linkedlist-in-dsa -title: LinkedList in Data Structures and Algorithms -sidebar_label: LinkedList -sidebar_position: 2 -description: "A linked list is a linear data structure in which elements are not stored in contiguous memory locations. Instead, each element, called a node, contains a data part and a reference (or link) to the next node in the sequence. Linked lists are used in various applications such as dynamic memory allocation, implementation of data structures like stacks and queues, and more." -tags: - [ - dsa, - data-structures, - linkedlist, - linked-list, - linkedlist-data-structure, - linkedlist-in-dsa, - linkedlist-in-data-structure, - linkedlist-in-algorithm, - linkedlist-in-dsa-example, - linkedlist-in-dsa-explanation, - linkedlist-in-dsa-conclusion, - linkedlist-in-dsa-importance, - linkedlist-in-dsa-syntax, - linkedlist-in-dsa-declaration, - linkedlist-in-dsa-access, - linkedlist-in-dsa-update, - linkedlist-in-dsa-insertion, - linkedlist-in-dsa-deletion, - linkedlist-in-dsa-traversal, - linkedlist-in-dsa-program, - linkedlist-in-dsa-code, - linkedlist-in-dsa-js, - linkedlist-in-dsa-java, - linkedlist-in-dsa-python, - linkedlist-in-dsa-c, - linkedlist-in-dsa-cpp, - linkedlist-in-dsa-ts, - ] ---- - -A linked list is a linear data structure in which elements are not stored in contiguous memory locations. Instead, each element, called a node, contains a data part and a reference (or link) to the next node in the sequence. Linked lists are used in various applications such as dynamic memory allocation, implementation of data structures like stacks and queues, and more. - -## Why are Linked Lists important? - -Linked lists are important because they provide a flexible way to store and manipulate data. They allow for efficient insertion and deletion of elements, which can be particularly useful in applications where the size of the data set changes frequently. - -## How to declare a Linked List? - -A linked list can be declared in various programming languages using the following syntax: - -# LinkedList in Data Structures and Algorithms (DSA) - -## Introduction - -A linked list is a fundamental data structure in computer science that represents a sequence of nodes. Each node contains data and a reference to the next node in the sequence. - -## Types of Linked Lists - -- **Singly Linked List**: Each node points to the next node and the last node points to null. -- **Doubly Linked List**: Each node points to both the next and the previous nodes. -- **Circular Linked List**: The last node points to the first node, forming a circle. -- **Circular Doubly Linked List**: Combines properties of both circular and doubly linked lists. - -## Basic Operations - -- **Insertion**: Adding a node to the linked list. -- **Deletion**: Removing a node from the linked list. -- **Traversal**: Accessing each node of the linked list. -- **Search**: Finding a node with a specific value. -- **Update**: Modifying the value of an existing node. - -## Why are Linked Lists important? - -Linked lists are important because they provide a flexible way to store and manipulate data. They allow for efficient insertion and deletion of elements, which can be particularly useful in applications where the size of the data set changes frequently. - -## How to declare a Linked List? - -A linked list can be declared in various programming languages using the following syntax: - - - - - ```js - // Node class in JavaScript - class Node { - constructor(data) { - this.data = data; - this.next = null; - } - } - - // LinkedList class in JavaScript - class LinkedList { - constructor() { - this.head = null; - } - - // Add a node at the end - append(data) { - let newNode = new Node(data); - if (this.head === null) { - this.head = newNode; - return; - } - let current = this.head; - while (current.next) { - current = current.next; - } - current.next = newNode; - } - } - ``` - - - - ```java - // Node class in Java - class Node { - int data; - Node next; - Node(int d) { data = d; next = null; } - } - - // LinkedList class in Java - public class LinkedList { - Node head; - - // Add a node at the end - public void append(int data) { - Node newNode = new Node(data); - if (head == null) { - head = newNode; - return; - } - Node current = head; - while (current.next != null) { - current = current.next; - } - current.next = newNode; - } - } - ``` - - - - ```python - # Node class in Python - class Node: - def __init__(self, data): - self.data = data - self.next = None - - # LinkedList class in Python - class LinkedList: - def __init__(self): - self.head = None - - # Add a node at the end - def append(self, data): - new_node = Node(data) - if self.head is None: - self.head = new_node - return - last = self.head - while last.next: - last = last.next - last.next = new_node - ``` - - - - ```c - // Node structure in C - struct Node { - int data; - struct Node* next; - }; - - // LinkedList structure in C - struct LinkedList { - struct Node* head; - }; - - // Function to create a new node - struct Node* createNode(int data) { - struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); - newNode->data = data; - newNode->next = NULL; - return newNode; - } - - // Function to add a node at the end - void append(struct LinkedList* list, int data) { - struct Node* newNode = createNode(data); - if (list->head == NULL) { - list->head = newNode; - return; - } - struct Node* temp = list->head; - while (temp->next != NULL) { - temp = temp->next; - } - temp->next = newNode; - } - ``` - - - - ```cpp - // Node class in C++ - class Node { - public: - int data; - Node* next; - Node(int d) { data = d; next = nullptr; } - }; - - // LinkedList class in C++ - class LinkedList { - public: - Node* head; - LinkedList() { head = nullptr; } - - // Add a node at the end - void append(int data) { - Node* newNode = new Node(data); - if (head == nullptr) { - head = newNode; - return; - } - Node* current = head; - while (current->next != nullptr) { - current = current->next; - } - current->next = newNode; - } - }; - ``` - - - - ```ts - // Node class in TypeScript - class Node { - data: number; - next: Node | null; - - constructor(data: number) { - this.data = data; - this.next = null; - } - } - - // LinkedList class in TypeScript - class LinkedList { - head: Node | null; - - constructor() { - this.head = null; - } - - // Add a node at the end - append(data: number): void { - let newNode = new Node(data); - if (this.head === null) { - this.head = newNode; - return; - } - let current = this.head; - while (current.next !== null) { - current = current.next; - } - current.next = newNode; - } - } - ``` - - - -## How to access a Linked List? - -A linked list can be accessed by traversing the nodes starting from the head. - - - - - ```js - // Access elements in a LinkedList in JavaScript - let list = new LinkedList(); - list.append(10); - list.append(20); - list.append(30); - - let current = list.head; - while (current !== null) { - console.log(current.data); - current = current.next; - } - ``` - - - - ```java - // Access elements in a LinkedList in Java - LinkedList list = new LinkedList(); - list.append(10); - list.append(20); - list.append(30); - - Node current = list.head; - while (current != null) { - System.out.println(current.data); - current = current.next; - } - ``` - - - - ```python - # Access elements in a LinkedList in Python - list = LinkedList() - list.append(10) - list.append(20) - list.append(30) - - current = list.head - while current: - print(current.data) - current = current.next - ``` - - - - ```c - // Access elements in a LinkedList in C - struct LinkedList list; - list.head = NULL; - append(&list, 10); - append(&list, 20); - append(&list, 30); - - struct Node* current = list.head; - while (current != NULL) { - printf("%d\n", current->data); - current = current->next; - } - ``` - - - - ```cpp - // Access elements in a LinkedList in C++ - LinkedList list; - list.append(10); - list.append(20); - list.append(30); - - Node* current = list.head; - while (current != nullptr) { - std::cout << current->data << std::endl; - current = current->next; - } - ``` - - - - ```ts - // Access elements in a LinkedList in TypeScript - let list = new LinkedList(); - list.append(10); - list.append(20); - list.append(30); - - let current = list.head; - while (current !== null) { - console.log(current.data); - current = current.next; - } - ``` - - - -## How to update a Linked List? - -A linked list can be updated by changing the data of a node directly. - - - - - ```js - // Update elements in a LinkedList in JavaScript - let list = new LinkedList(); - list.append(10); - list.append(20); - list.append(30); - - let current = list.head; - while (current !== null) { - if (current.data === 20) { - current.data = 25; - } - current = current.next; - } - ``` - - - - ```java - // Update elements in a LinkedList in Java - LinkedList list = new LinkedList(); - list.append(10); - list.append(20); - list.append(30); - - Node current = list.head; - while (current != null) { - if (current.data == 20) { - current.data = 25; - } - current = current.next; - } - ``` - - - - ```python - # Update elements in a LinkedList in Python - list = LinkedList() - list.append(10) - list.append(20) - list.append(30) - - current = list.head - while current: - if current.data == 20: - current.data = 25 - current = current.next - ``` - - - - ```c - // Update elements in a LinkedList in C - struct LinkedList list; - list.head = NULL; - append(&list, 10); - append(&list, 20); - append(&list, 30); - - struct Node* current = list.head; - while (current != NULL) { - if (current->data == 20) { - current->data = 25; - } - current = current->next; - } - ``` - - - - ```cpp - // Update elements in a LinkedList in C++ - LinkedList list; - list.append(10); - list.append(20); - list.append(30); - - Node* current = list.head; - while (current != nullptr) { - if (current->data == 20) { - current->data = 25; - } - current = current->next; - } - ``` - - - - ```ts - // Update elements in a LinkedList in TypeScript - let list = new LinkedList(); - list.append(10); - list.append(20); - list.append(30); - - let current = list.head; - while (current !== null) { - if (current.data === 20) { - current.data = 25; - } - current = current.next; - } - ``` - - - -## How to delete a node from a Linked List? - -A node can be deleted from a linked list by adjusting the links of the adjacent nodes. - - - - - ```js - // Delete a node from a LinkedList in JavaScript - class LinkedList { - // ... - delete(data) { - if (this.head === null) return; - if (this.head.data === data) { - this.head = this.head.next; - return; - } - let current = this.head; - while (current.next !== null) { - if (current.next.data === data) { - current.next = current.next.next; - return; - } - current = current.next; - } - } - } - ``` - - - - ```java - // Delete a node from a LinkedList in Java - public class LinkedList { - // ... - public void delete(int data) { - if (head == null) return; - if (head.data == data) { - head = head.next; - return; - } - Node current = head; - while (current.next != null) { - if (current.next.data == data) { - current.next = current.next.next; - return; - } - current = current.next; - } - } - } - ``` - - - - ```python - # Delete a node from a LinkedList in Python - class LinkedList: - # ... - def delete(self, data): - if self.head is None: - return - if self.head.data == data: - self.head = self.head.next - return - current = self.head - while current.next: - if current.next.data == data: - current.next = current.next.next - return - current = current.next - ``` - - - - ```c - // Delete a node from a LinkedList in C - void deleteNode(struct LinkedList* list, int data) { - if (list->head == NULL) return; - struct Node* temp = list->head; - if (temp->data == data) { - list->head = temp->next; - free(temp); - return; - } - struct Node* prev = NULL; - while (temp != NULL && temp->data != data) { - prev = temp; - temp = temp->next; - } - if (temp == NULL) return; - prev->next = temp->next; - free(temp); - } - ``` - - - - ```cpp - // Delete a node from a LinkedList in C++ - class LinkedList { - // ... - void deleteNode(int data) { - if (head == nullptr) return; - Node* temp = head; - if (temp->data == data) { - head = temp->next; - delete temp; - return; - } - Node* prev = nullptr; - while (temp != nullptr && temp->data != data) { - prev = temp; - temp = temp->next; - } - if (temp == nullptr) return; - prev->next = temp->next; - delete temp; - } - }; - ``` - - - - ```ts - // Delete a node from a LinkedList in TypeScript - class LinkedList { - // ... - delete(data: number) { - if (this.head === null) return; - if (this.head.data === data) { - this.head = this.head.next; - return; - } - let current = this.head; - while (current.next !== null) { - if (current.next.data === data) { - current.next = current.next.next; - return; - } - current = current.next; - } - } - } - ``` - - - -## Applications of Linked Lists - -- **Dynamic memory allocation**: Linked lists can efficiently manage memory allocation and deallocation. -- **Implementation of stacks and queues**: Linked lists provide the foundation for stack and queue data structures. -- **Graph representation**: Adjacency lists use linked lists to represent graphs. -- **Handling sparse matrices**: Linked lists efficiently store and manipulate sparse matrices. - -## Common Linked List Problems - -- **Reverse a Linked List**: Reversing the nodes of a linked list. -- **Detect a cycle in a Linked List**: Checking if a linked list contains a cycle. -- **Merge two sorted Linked Lists**: Combining two sorted linked lists into one sorted linked list. -- **Find the middle of a Linked List**: Finding the middle node in a linked list. - -## Advanced Linked List Variants - -- **Doubly Linked List**: A linked list where each node has references to both the next and previous nodes. -- **Circular Linked List**: A linked list where the last node points back to the first node. -- **Skip List**: A linked list with additional pointers for faster search. - -## Resources and References - -- **Books**: - - "Introduction to Algorithms" by Cormen, Leiserson, Rivest, and Stein - - "Data Structures and Algorithm Analysis in C" by Mark Allen Weiss -- **Online Courses**: - - Coursera: Data Structures and Algorithms Specialization - - edX: Data Structures Fundamentals -- **Websites**: - - [GeeksforGeeks](https://www.geeksforgeeks.org) - - [LeetCode](https://leetcode.com) - - [HackerRank](https://www.hackerrank.com) - ---- - -By understanding and mastering these linked list concepts and algorithms, you will be well-equipped to tackle a wide range of problems in data structures and algorithms. - -## Conclusion - -Linked lists are a fundamental data structure in computer science and play a crucial role in various applications and algorithms. This guide covers the essential concepts and operations associated with linked lists, providing a comprehensive understanding of how they work and how to implement them in different programming languages. - -Understanding linked lists is crucial for solving numerous problems in computer science, from basic data manipulation to complex algorithms in dynamic memory allocation, graph representation, and more. The examples provided demonstrate how to work with linked lists efficiently, ensuring a robust foundation for tackling more advanced DSA concepts. Mastery of linked lists enhances your ability to handle data structures and perform operations crucial in both everyday programming and competitive coding. - -Problems for Practice -To further practice and test your understanding of linked lists, consider solving the following problems from LeetCode: - -1. Reverse Linked List -2. Linked List Cycle -3. Merge Two Sorted Lists -4. Remove Nth Node From End of List -5. Add Two Numbers - -Engaging with these problems will help reinforce the concepts learned and provide practical experience in using linked lists effectively. By practicing these problems, you will enhance your problem-solving skills and deepen your understanding of linked list manipulation in various contexts. diff --git a/docs/dsa/linkedlist/LinkedListProblems.md b/docs/dsa/linkedlist/LinkedListProblems.md deleted file mode 100644 index 5c727033b..000000000 --- a/docs/dsa/linkedlist/LinkedListProblems.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -id: leetcode-linkedlist-problems -title: LeetCode LinkedList Problems -sidebar_label: LinkedList Problems -sidebar_position: 1 -description: "A collection of easy, medium, and hard LinkedList problems from LeetCode to help you practice and master LinkedList concepts in Data Structures and Algorithms." -tags: - [ - dsa, - data-structures, - linkedlist, - leetcode, - linkedlist-problems, - linkedlist-in-dsa, - linkedlist-in-data-structure, - linkedlist-in-algorithm, - linkedlist-in-dsa-example, - linkedlist-in-dsa-explanation, - linkedlist-in-dsa-conclusion, - linkedlist-in-dsa-importance, - linkedlist-in-dsa-syntax, - linkedlist-in-dsa-declaration, - linkedlist-in-dsa-access, - linkedlist-in-dsa-update, - linkedlist-in-dsa-delete, - linkedlist-in-dsa-iterate, - linkedlist-in-dsa-max-min, - linkedlist-in-dsa-program, - linkedlist-in-dsa-code, - linkedlist-in-dsa-js, - linkedlist-in-dsa-java, - linkedlist-in-dsa-python, - linkedlist-in-dsa-c, - linkedlist-in-dsa-cpp, - linkedlist-in-dsa-ts, - ] ---- - -# LeetCode LinkedList Problems - -## Easy Problems - -1. [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) - - - Problem: Reverse a singly linked list. - - LeetCode ID: 206 - -2. [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) - - - Problem: Remove all elements from a linked list of integers that have value val. - - LeetCode ID: 203 - -3. [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) - - - Problem: Check if a linked list is a palindrome. - - LeetCode ID: 234 - -4. [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) - - - Problem: Merge two sorted linked lists and return it as a new sorted list. - - LeetCode ID: 21 - -5. [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) - - - Problem: Determine if a linked list has a cycle. - - LeetCode ID: 141 - -6. [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) - - - Problem: Delete all duplicates such that each element appears only once. - - LeetCode ID: 83 - -7. [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) - - Problem: Find the node at which the intersection of two singly linked lists begins. - - LeetCode ID: 160 - -## Medium Problems - -1. [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) - - - Problem: Add two numbers represented by linked lists. - - LeetCode ID: 2 - -2. [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) - - - Problem: Group all odd nodes together followed by the even nodes. - - LeetCode ID: 328 - -3. [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) - - - Problem: Remove the nth node from the end of the list. - - LeetCode ID: 19 - -4. [Reorder List](https://leetcode.com/problems/reorder-list/) - - - Problem: Reorder the list to follow a specific order. - - LeetCode ID: 143 - -5. [Rotate List](https://leetcode.com/problems/rotate-list/) - - - Problem: Rotate the list to the right by k places. - - LeetCode ID: 61 - -6. [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) - - - Problem: Swap every two adjacent nodes. - - LeetCode ID: 24 - -7. [Partition List](https://leetcode.com/problems/partition-list/) - - Problem: Partition the list so that nodes less than x come before nodes greater than or equal to x. - - LeetCode ID: 86 - -## Hard Problems - -1. [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) - - - Problem: Merge k sorted linked lists and return it as one sorted list. - - LeetCode ID: 23 - -2. [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) - - - Problem: Reverse the nodes of a linked list k at a time. - - LeetCode ID: 25 - -3. [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) - - - Problem: A linked list with a random pointer, deep copy the list. - - LeetCode ID: 138 - -4. [LRU Cache](https://leetcode.com/problems/lru-cache/) - - - Problem: Design and implement a data structure for Least Recently Used (LRU) cache. - - LeetCode ID: 146 - -5. [Flatten a Multilevel Doubly Linked List](https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/) - - - Problem: Flatten a multilevel doubly linked list. - - LeetCode ID: 430 - -6. [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) - - Problem: Return a random node's value from the linked list. - - LeetCode ID: 382 - -## Conclusion - -Practicing these problems will help reinforce the concepts learned and provide practical experience in using linked lists effectively. By solving these problems, you will enhance your problem-solving skills and deepen your understanding of linked list manipulation in various contexts. diff --git a/docs/dsa/linkedlist/_category_.json b/docs/dsa/linkedlist/_category_.json deleted file mode 100644 index 471f3ca54..000000000 --- a/docs/dsa/linkedlist/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "LinkedList", - "position": 9, - "link": { - "type": "generated-index", - "description": "In data structures, Linked List is basically chains of nodes where each node contains information such as data and a pointer to the next node in the chain. It is a popular data structure with a wide range of real-world applications. In this article, we will provide a complete introduction of Linked List, which will help you tackle any problem based on Linked List." - } -} diff --git a/docs/dsa/master-theorem.md b/docs/dsa/master-theorem.md deleted file mode 100644 index 7b0bbcb89..000000000 --- a/docs/dsa/master-theorem.md +++ /dev/null @@ -1,209 +0,0 @@ ---- -id: master-theorem -title: Master Theorem for Divide and Conquer Recurrences -sidebar_label: Master Theorem -sidebar_position: 3 -description: "Master Theorem for solving divide and conquer recurrences. Explained with examples." -tags: - [ - dsa, - data-structures, - algorithms, - divide-and-conquer, - master-theorem, - recurrences, - ] ---- - -Master Theorem is a popular technique to solve recurrence relations of divide and conquer algorithms. It provides a way to determine the time complexity of recursive algorithms. The theorem is used to solve recurrences of the form: - -$$ - \boldsymbol{{T(n)} = aT \frac{n}{b} + f(n)} -$$ - -where: - -- $T(n)$ is the time complexity of the algorithm. -- $a$ is the number of subproblems in the recursion. -- $\frac{n}{b}$ is the size of each subproblem. -- $f(n)$ is the time complexity of the work done outside the recursive calls. -- $n$ is the size of the input. -- $a \geq 1$ and $b > 1$ are constants. -- $f(n)$ is a function that is asymptotically positive. -- $T(n)$ is defined on non-negative integers. -- The recurrence relation is defined for $n \geq n_0$ for some constant $n_0$. - -The Master Theorem provides a way to determine the time complexity of the algorithm based on the values of `a`, `b`, and `f(n)`. - -## Master Theorem Cases {#master-theorem-cases} - -The Master Theorem has three cases based on the comparison of `f(n)` with `n^log_b(a)`: - -1. **Case 1**: If `f(n) = O(n^log_b(a - ε))` for some constant `ε > 0`, then `T(n) = Θ(n^log_b(a))`. -2. **Case 2**: If `f(n) = Θ(n^log_b(a))`, then `T(n) = Θ(n^log_b(a) * log(n))`. -3. **Case 3**: If `f(n) = Ω(n^log_b(a + ε))` for some constant `ε > 0`, if `a * f(n/b) <= c * f(n)` for some constant `c < 1` and sufficiently large `n`, then `T(n) = Θ(f(n))`. - -## Example {#example} - -Let's consider the recurrence relation for the Merge Sort algorithm: - -$ - \boldsymbol{{T(n)} = aT \frac{n}{b} + f(n)} -$ - -Here: - -- `a = 2` (number of subproblems). -- `b = 2` (size of each subproblem). -- `f(n) = Θ(n)` (time complexity of work done outside the recursive calls). -- `n` is the size of the input. -- `n0 = 1`. -- `f(n)` is asymptotically positive. -- `a >= 1` and `b > 1`. -- The recurrence relation is defined for `n >= n0`. -- The relation is of the form `T(n) = aT(n/b) + f(n)`. - -Now, let's compare `f(n)` with `n^log_b(a)`: - -- `n^log_b(a) = n^log_2(2) = n`. -- `f(n) = Θ(n)`. -- `f(n) = Θ(n) = n^log_b(a)`. - -Since `f(n) = Θ(n) = n^log_b(a)`, the recurrence relation falls under **Case 2** of the Master Theorem. Therefore, the time complexity of the Merge Sort algorithm is `T(n) = Θ(n * log(n))`. - -## Conclusion {#conclusion} - -The Master Theorem provides a way to determine the time complexity of divide and conquer algorithms. It simplifies the process of solving recurrence relations and helps in analyzing the time complexity of recursive algorithms. By comparing the function `f(n)` with `n^log_b(a)`, the Master Theorem classifies the recurrence relation into one of the three cases and provides the time complexity of the algorithm. - -Master Theorem is a powerful tool to analyze the time complexity of divide and conquer algorithms. It is widely used in the analysis of recursive algorithms to determine their time complexity. - -## Implementations - - - - ```js - function masterTheorem(a, b, f, n) { - if (a < 1 || b < 1) { - return "Invalid input"; - } - - const logBaseB = Math.log(a) / Math.log(b); - - if (f === n ** logBaseB) { - return `T(n) = Θ(n^${logBaseB} * log(n))`; - } else if (f < n ** logBaseB) { - return `T(n) = Θ(n^${logBaseB})`; - } else { - return "Case 3: Not covered by Master Theorem"; - } - } - ``` - - - ```java - public class MasterTheorem { - public static String masterTheorem(int a, int b, int f, int n) { - if (a < 1 || b < 1) { - return "Invalid input"; - } - - double logBaseB = Math.log(a) / Math.log(b); - - if (f == Math.pow(n, logBaseB)) { - return String.format("T(n) = Θ(n^%.2f * log(n))", logBaseB); - } else if (f < Math.pow(n, logBaseB)) { - return String.format("T(n) = Θ(n^%.2f)", logBaseB); - } else { - return "Case 3: Not covered by Master Theorem"; - } - } - - public static void main(String[] args) { - System.out.println(masterTheorem(2, 2, 2, 2)); - } - } - ``` - - - - ```python - def master_theorem(a, b, f, n): - if a < 1 or b < 1: - return "Invalid input" - - log_base_b = a / b - - if f == n ** log_base_b: - return f"T(n) = Θ(n^{log_base_b} * log(n))" - elif f < n ** log_base_b: - return f"T(n) = Θ(n^{log_base_b})" - else: - return "Case 3: Not covered by Master Theorem" - ``` - - - - ```cpp - #include - #include - #include - - std::string masterTheorem(int a, int b, int f, int n) { - if (a < 1 || b < 1) { - return "Invalid input"; - } - - double logBaseB = log(a) / log(b); - - if (f == pow(n, logBaseB)) { - return "T(n) = Θ(n^" + std::to_string(logBaseB) + " * log(n))"; - } else if (f < pow(n, logBaseB)) { - return "T(n) = Θ(n^" + std::to_string(logBaseB) + ")"; - } else { - return "Case 3: Not covered by Master Theorem"; - } - } - - int main() { - std::cout << masterTheorem(2, 2, 2, 2) << std::endl; - return 0; - } - ``` - - - - -## Live Coding Implementation - -```jsx live -function MasterTheoremExample() { - const a = 2, - b = 2, - f = 2, - n = 4; - - function MasterTheorem(a, b, f, n) { - if (a < 1 || b < 1) { - return `Invalid input`; - } - - const logBaseB = Math.log(a) / Math.log(b); - - if (f === n ** logBaseB) { - return `T(n) = Θ(n^${logBaseB} * log(n))`; - } else if (f < n ** logBaseB) { - return `T(n) = Θ(n^${logBaseB})`; - } else { - return `Case 3: Not covered by Master Theorem`; - } - } - - return ( -
-

- Output: {MasterTheorem(a, b, f, n)} -

-
- ); -} -``` diff --git a/docs/dsa/recursion/_category_.json b/docs/dsa/recursion/_category_.json deleted file mode 100644 index 1af68bcf8..000000000 --- a/docs/dsa/recursion/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Recursion", - "position": 10, - "link": { - "type": "generated-index", - "description": "In data structures, The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. " - } -} diff --git a/docs/dsa/recursion/recursion.md b/docs/dsa/recursion/recursion.md deleted file mode 100644 index ff8563344..000000000 --- a/docs/dsa/recursion/recursion.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -id: recursion-in-dsa -title: Recursion in Data Structures and Algorithms -sidebar_label: Recursion -sidebar_position: 3 -description: "Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. It is used in various applications such as solving mathematical problems, implementing data structures, and more." -tags: - [ - dsa, - algorithms, - recursion, - recursive-functions, - recursion-in-dsa, - recursion-in-algorithm, - recursion-in-dsa-example, - recursion-in-dsa-explanation, - recursion-in-dsa-conclusion, - recursion-in-dsa-importance, - recursion-in-dsa-syntax, - recursion-in-dsa-implementation, - recursion-in-dsa-applications, - recursion-in-dsa-problems, - recursion-in-dsa-solutions, - recursion-in-dsa-code, - recursion-in-dsa-js, - recursion-in-dsa-java, - recursion-in-dsa-python, - recursion-in-dsa-c, - recursion-in-dsa-cpp, - recursion-in-dsa-ts, - ] ---- - -Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. It is used in various applications such as solving mathematical problems, implementing data structures, and more. - -## Why is Recursion important? - -Recursion is important because it provides a simple and elegant way to solve complex problems. It allows problems to be broken down into smaller, more manageable subproblems, making it easier to understand and implement solutions. - -## How to implement Recursion? - -Recursion can be implemented in various programming languages using the following syntax: - -## Recursive Function Structure - -```python -def recursive_function(parameters): - if base_condition(parameters): - return base_case_value - else: - return recursive_function(modified_parameters) -``` - -## Examples of Recursive Functions - -### Factorial - - - - - ```js - function factorial(n) { - if (n === 0) { - return 1; - } - return n * factorial(n - 1); - } - ``` - - - - ```java - public class RecursionExample { - public static int factorial(int n) { - if (n == 0) { - return 1; - } - return n * factorial(n - 1); - } - } - ``` - - - - ```python - def factorial(n): - if n == 0: - return 1 - return n * factorial(n - 1) - ``` - - - - ```c - int factorial(int n) { - if (n == 0) { - return 1; - } - return n * factorial(n - 1); - } - ``` - - - - ```cpp - int factorial(int n) { - if (n == 0) { - return 1; - } - return n * factorial(n - 1); - } - ``` - - - - ```ts - function factorial(n: number): number { - if (n === 0) { - return 1; - } - return n * factorial(n - 1); - } - ``` - - -Fibonacci - - - - ```js - function fibonacci(n) { - if (n <= 1) { - return n; - } - return fibonacci(n - 1) + fibonacci(n - 2); - } - ``` - - - - ```java - public class RecursionExample { - public static int fibonacci(int n) { - if (n <= 1) { - return n; - } - return fibonacci(n - 1) + fibonacci(n - 2); - } - } - ``` - - - - ```python - def fibonacci(n): - if n <= 1: - return n - return fibonacci(n - 1) + fibonacci(n - 2) - ``` - - - - ```c - int fibonacci(int n) { - if (n <= 1) { - return n; - } - return fibonacci(n - 1) + fibonacci(n - 2); - } - ``` - - - - ```cpp - int fibonacci(int n) { - if (n <= 1) { - return n; - } - return fibonacci(n - 1) + fibonacci(n - 2); - } - ``` - - - - ```ts - function fibonacci(n: number): number { - if (n <= 1) { - return n; - } - return fibonacci(n - 1) + fibonacci(n - 2); - } - ``` - - - -## Applications of Recursion - -1. Mathematical computations: Factorial, Fibonacci series, power functions, etc. -2. Data structures: Tree and graph traversals. -3. Algorithm design: Divide and conquer algorithms like merge sort and quicksort. -4. Dynamic programming: Recursive definitions with memoization. -5. Common Recursive Problems -6. Tower of Hanoi: Moving disks between rods following specific rules. -7. Permutations and combinations: Generating all possible arrangements or selections. -8. Backtracking: Solving puzzles and constraint satisfaction problems. - -## Advanced Recursive Techniques - -1. Tail Recursion: A special form of recursion where the recursive call is the last statement in the function. Optimized by compilers to prevent stack overflow. -2. Memoization: Caching the results of expensive function calls to improve performance. - -## Resources and References - -### Books: - -1. "Introduction to Algorithms" by Cormen, Leiserson, Rivest, and Stein -2. "The Art of Computer Programming" by Donald Knuth - -### Online Courses: - -1. Coursera: Data Structures and Algorithms Specialization -2. edX: Algorithms and Data Structures - -### Websites: - -1. GeeksforGeeks -2. LeetCode -3. HackerRank - -By understanding and mastering these recursion concepts and techniques, you will be well-equipped to tackle a wide range of problems in data structures and algorithms. - -## Conclusion - -Recursion is a powerful technique in computer science that enables elegant and efficient solutions to complex problems. This guide covers the essential concepts and applications of recursion, providing a comprehensive understanding of how to implement and utilize recursive functions in different programming languages. - -Understanding recursion is crucial for solving numerous problems in computer science, from basic mathematical computations to complex algorithm design. The examples provided demonstrate how to work with recursion effectively, ensuring a robust foundation for tackling more advanced DSA concepts. Mastery of recursion enhances your ability to handle algorithmic challenges and perform operations crucial in both everyday programming and competitive coding. - -## Problems for Practice - -To further practice and test your understanding of recursion, consider solving the following problems from LeetCode: - -1. Fibonacci Number -2. Climbing Stairs -3. Permutations -4. Subsets -5. Combination Sum - - - Engaging with these problems will help reinforce the concepts learned and provide practical experience in using recursion effectively. By practicing these problems, you will enhance your problem-solving skills and deepen your understanding of recursive algorithms in various contexts. diff --git a/docs/dsa/recursion/recursionVsIteration.md b/docs/dsa/recursion/recursionVsIteration.md deleted file mode 100644 index 84d0b0067..000000000 --- a/docs/dsa/recursion/recursionVsIteration.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -id: recursion-vs-iteration-in-dsa -title: Difference between Recursion and Iteration in Data Structures and Algorithms -sidebar_label: Recursion vs Iteration -sidebar_position: 3 -description: "Understanding the differences between recursion and iteration is crucial for selecting the appropriate approach for solving various problems in data structures and algorithms. This guide highlights the key differences, advantages, and use cases of both recursion and iteration." -tags: - [ - dsa, - data-structures, - algorithms, - recursion, - iteration, - recursion-vs-iteration, - recursion-in-dsa, - iteration-in-dsa, - recursion-vs-iteration-in-dsa, - recursion-vs-iteration-examples, - recursion-vs-iteration-differences, - recursion-vs-iteration-advantages, - recursion-vs-iteration-disadvantages, - recursion-vs-iteration-usage, - ] ---- - -Understanding the differences between recursion and iteration is crucial for selecting the appropriate approach for solving various problems in data structures and algorithms. This guide highlights the key differences, advantages, and use cases of both recursion and iteration. - -## Introduction - -### Recursion - -Recursion is a technique where a function calls itself in order to solve a smaller instance of the same problem until a base case is reached. Recursive solutions can be elegant and easy to understand but may come with performance overheads due to repeated function calls. - -### Iteration - -Iteration involves using loops (such as for, while, or do-while) to repeat a block of code until a certain condition is met. Iterative solutions are often more efficient in terms of memory usage and execution time compared to recursion, but they can be less intuitive for problems that have a naturally recursive structure. - -## Key Differences - -| Feature | Recursion | Iteration | -| ------------ | ------------------------------------------------------ | ------------------------------------------- | -| Definition | Function calls itself | Loop repeatedly executes block of code | -| Termination | Base case | Loop condition | -| Memory Usage | Uses call stack, can lead to stack overflow | Uses constant or linear memory | -| Readability | Often more readable for problems with recursive nature | Can be less readable for complex conditions | -| Performance | Higher overhead due to function calls | Generally more efficient | -| Use Cases | Divide and conquer, tree and graph traversal | Simple loops, repetitive tasks | - -## Examples - -### Factorial Calculation - -#### Recursion - -```python -def factorial(n): - if n == 0: - return 1 - else: - return n * factorial(n - 1) -``` - -#### Iteration - -```python -def factorial(n): - result = 1 - for i in range(1, n + 1): - result *= i - return result -``` - -### Fibonacci Series - -#### Recursion - -```python -def fibonacci(n): - if n <= 1: - return n - else: - return fibonacci(n - 1) + fibonacci(n - 2) -``` - -#### Iteration - -```python -def fibonacci(n): - a, b = 0, 1 - for _ in range(n): - a, b = b, a + b - return a -``` - -## Advantages and Disadvantages - -### Recursion - -#### Advantages: - - 1. Simplifies the code for problems that have a natural recursive structure. - 2. Makes the code easier to write and understand for problems like tree traversals. - -#### Disadvantages: - - 1. Can lead to stack overflow if the recursion depth is too large. - 2. Generally less efficient in terms of time and space due to function call overhead. - -### Iteration - -#### Advantages: - - 1. More efficient in terms of memory and execution time. - 2. Avoids the risk of stack overflow. - -#### Disadvantages: - - 1. Can result in more complex and less readable code for problems with recursive nature. - 2. Requires explicit management of loop conditions and state. - -## When to Use Recursion vs Iteration - -### Use Recursion When: - -The problem has a naturally recursive structure (e.g., tree and graph traversal). -Code readability and simplicity are more important than performance. -You are dealing with divide-and-conquer algorithms (e.g., quicksort, mergesort). - -### Use Iteration When: - -Performance and memory efficiency are critical. -The problem involves simple repetitive tasks or loops. -You want to avoid the risk of stack overflow for deep recursion. - -## Conclusion - -Both recursion and iteration are fundamental techniques in data structures and algorithms, each with its own strengths and weaknesses. The choice between recursion and iteration depends on the specific problem at hand, the importance of performance and memory usage, and the need for code readability and simplicity. By understanding the differences and appropriate use cases for each approach, you can make informed decisions in your algorithmic implementations. - -## Resources and References - -#### Books: - - 1. "Introduction to Algorithms" by Cormen, Leiserson, Rivest, and Stein - 2. "Data Structures and Algorithm Analysis in C" by Mark Allen Weiss - -#### Online Courses: - - 1. Coursera: Data Structures and Algorithms Specialization - 2. edX: Algorithms and Data Structures - -#### Websites: - - 1. GeeksforGeeks - 2. LeetCode - 3. HackerRank - - Understanding and mastering both recursion and iteration will significantly enhance your ability to solve a wide range of problems in data structures and algorithms. This guide provides a comprehensive overview of the differences, advantages, and use cases for each approach, enabling you to make the best choice for your specific needs. diff --git a/docs/dsa/recursion/recursion_leetcode_questions.md b/docs/dsa/recursion/recursion_leetcode_questions.md deleted file mode 100644 index 3010abf3c..000000000 --- a/docs/dsa/recursion/recursion_leetcode_questions.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -id: recursion-leetcode-questions -title: Recursion Leetcode Questions -sidebar_label: Recursion Leetcode Questions -sidebar_position: 4 -description: "A collection of 20 Leetcode questions focused on recursion, categorized into easy, medium, and hard levels." -tags: - [ - dsa, - data-structures, - algorithms, - recursion, - leetcode, - recursion-leetcode, - recursion-leetcode-easy, - recursion-leetcode-medium, - recursion-leetcode-hard, - recursion-leetcode-questions, - ] ---- - -A collection of 20 Leetcode questions focused on recursion, categorized into easy, medium, and hard levels. - -## Easy - -1. **[Factorial](https://leetcode.com/problems/factorial)** - - Description: Calculate the factorial of a given number using recursion. -2. **[Fibonacci Number](https://leetcode.com/problems/fibonacci-number)** - - Description: Compute the n-th Fibonacci number using recursion. -3. **[Reverse String](https://leetcode.com/problems/reverse-string)** - - Description: Reverse a string using recursion. -4. **[Sum of Digits of a Number](https://leetcode.com/problems/sum-of-digits-of-a-number)** - - Description: Find the sum of digits of a given number using recursion. -5. **[Power of Three](https://leetcode.com/problems/power-of-three)** - - Description: Determine if a number is a power of three using recursion. -6. **[Climbing Stairs](https://leetcode.com/problems/climbing-stairs)** - - Description: Find the number of ways to climb a staircase using recursion. -7. **[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list)** - - Description: Check if a linked list is a palindrome using recursion. -8. **[Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree)** - - Description: Find the maximum depth of a binary tree using recursion. - -## Medium - -1. **[Subsets](https://leetcode.com/problems/subsets)** - - Description: Generate all possible subsets of a set using recursion. -2. **[Permutations](https://leetcode.com/problems/permutations)** - - Description: Generate all possible permutations of a sequence using recursion. -3. **[Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii)** - - Description: Generate all unique BSTs that store values 1 to n using recursion. -4. **[Word Search](https://leetcode.com/problems/word-search)** - - Description: Search for a word in a 2D grid using recursion. -5. **[Combination Sum](https://leetcode.com/problems/combination-sum)** - - Description: Find all unique combinations of numbers that sum to a target using recursion. -6. **[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number)** - - Description: Generate all possible letter combinations that a phone number could represent using recursion. -7. **[Generate Parentheses](https://leetcode.com/problems/generate-parentheses)** - - Description: Generate all combinations of well-formed parentheses using recursion. - -## Hard - -1. **[N-Queens](https://leetcode.com/problems/n-queens)** - - Description: Solve the N-Queens problem using recursion. -2. **[Sudoku Solver](https://leetcode.com/problems/sudoku-solver)** - - Description: Solve a given Sudoku puzzle using recursion. -3. **[Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching)** - - Description: Implement regular expression matching with support for '.' and '\*' using recursion. -4. **[Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses)** - - Description: Find the length of the longest valid parentheses substring using recursion. -5. **[Interleaving String](https://leetcode.com/problems/interleaving-string)** - - Description: Determine if a string is an interleaving of two other strings using recursion. - ---- - -These questions provide a comprehensive overview of recursion techniques and are a great way to practice and improve your recursion skills in data structures and algorithms. diff --git a/docs/dsa/stack/_category_.json b/docs/dsa/stack/_category_.json deleted file mode 100644 index 9b32456bc..000000000 --- a/docs/dsa/stack/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Stack", - "position": 12, - "link": { - "type": "generated-index", - "description": "Stack is a linear data structure that follows LIFO principle" - } -} diff --git a/docs/dsa/stack/stack-using-array.md b/docs/dsa/stack/stack-using-array.md deleted file mode 100644 index 3dd65eb53..000000000 --- a/docs/dsa/stack/stack-using-array.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -id: stack-in-dsa -title: Stack Using Array -sidebar_label: Stack Using Array -sidebar_position: 1 -description: "Stack is a linear data structure that follows LIFO principle" -tags: [dsa, data-structures, stack, LIFO] ---- - -### Introduction to Stack - -A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Stacks are used in various applications such as expression evaluation, function call management in recursion, and more. - -### Stack Operations - -1. **Push**: Add an element to the top of the stack. -2. **Pop**: Remove the top element from the stack. -3. **Peek (or Top)**: Retrieve the top element of the stack without removing it. -4. **isEmpty**: Check if the stack is empty. -5. **Size**: Get the number of elements in the stack. - -### Pseudocode - -#### Basic Operations - -1. **Push**: - - ```text - function push(stack, element): - stack.append(element) - ``` - -2. **Pop**: - - ```text - function pop(stack): - if isEmpty(stack): - return "Stack Underflow" - return stack.pop() - ``` - -3. **Peek**: - - ```text - function peek(stack): - if isEmpty(stack): - return "Stack is empty" - return stack[-1] - ``` - -4. **isEmpty**: - - ```text - function isEmpty(stack): - return len(stack) == 0 - ``` - -5. **Size**: - ```text - function size(stack): - return len(stack) - ``` - -### Implementation in Python, C++, and Java - -#### Python Implementation - -```python -class Stack: - def __init__(self): - self.elements = [] - - def push(self, element): - self.elements.append(element) - - def pop(self): - if self.is_empty(): - return "Stack Underflow" - return self.elements.pop() - - def peek(self): - if self.is_empty(): - return "Stack is empty" - return self.elements[-1] - - def is_empty(self): - return len(self.elements) == 0 - - def size(self): - return len(self.elements) - -# Example usage -stack = Stack() -stack.push(10) -stack.push(20) -print(stack.pop()) # Output: 20 -print(stack.peek()) # Output: 10 -print(stack.is_empty()) # Output: False -print(stack.size()) # Output: 1 -``` - -#### C++ Implementation - -```cpp -#include -#include - -class Stack { -private: - std::vector.elements; - -public: - void push(int element) { - .elements.push_back(element); - } - - int pop() { - if (isEmpty()) { - std::cerr << "Stack Underflow" << std::endl; - return -1; - } - int top =.elements.back(); - .elements.pop_back(); - return top; - } - - int peek() { - if (isEmpty()) { - std::cerr << "Stack is empty" << std::endl; - return -1; - } - return.elements.back(); - } - - bool isEmpty() { - return.elements.empty(); - } - - int size() { - return.elements.size(); - } -}; - -// Example usage -int main() { - Stack stack; - stack.push(10); - stack.push(20); - std::cout << stack.pop() << std::endl; // Output: 20 - std::cout << stack.peek() << std::endl; // Output: 10 - std::cout << std::boolalpha << stack.isEmpty() << std::endl; // Output: false - std::cout << stack.size() << std::endl; // Output: 1 - return 0; -} -``` - -#### Java Implementation - -```java -import java.util.ArrayList; - -public class Stack { - private ArrayList.elements; - - public Stack() { - .elements = new ArrayList<>(); - } - - public void push(int element) { - .elements.add(element); - } - - public int pop() { - if (isEmpty()) { - System.out.println("Stack Underflow"); - return -1; - } - return.elements.remove.elements.size() - 1); - } - - public int peek() { - if (isEmpty()) { - System.out.println("Stack is empty"); - return -1; - } - return.elements.get.elements.size() - 1); - } - - public boolean isEmpty() { - return.elements.isEmpty(); - } - - public int size() { - return.elements.size(); - } - - // Example usage - public static void main(String[] args) { - Stack stack = new Stack(); - stack.push(10); - stack.push(20); - System.out.println(stack.pop()); // Output: 20 - System.out.println(stack.peek()); // Output: 10 - System.out.println(stack.isEmpty()); // Output: false - System.out.println(stack.size()); // Output: 1 - } -} -``` - -### Complexity - -- **Time Complexity**: - - - Push: $O(1)$ - - Pop: $O(1)$ - - Peek: $O(1)$ - - isEmpty: $O(1)$ - - Size: $O(1)$ - -- **Space Complexity**: $O(n)$, where $n$ is the number of elements in the stack. - -### Example - -Consider a stack with the following operations: - -1. Push 10 -2. Push 20 -3. Pop -4. Peek -5. Check if empty -6. Get size - -**Operations**: - -- Push 10: Stack becomes [10] -- Push 20: Stack becomes [10, 20] -- Pop: Removes 20, Stack becomes [10] -- Peek: Returns 10, Stack remains [10] -- isEmpty: Returns false -- Size: Returns 1 - -### Conclusion - -A stack is a fundamental data structure used in computer science for various applications where the LIFO (Last In First Out) principle is required. It is simple to implement and provides efficient operations for adding and removing elements. Understanding and using stacks effectively can help solve many algorithmic problems. diff --git a/docs/dsa/strings/_category_.json b/docs/dsa/strings/_category_.json deleted file mode 100644 index 5e94df7ac..000000000 --- a/docs/dsa/strings/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "String", - "position": 8, - "link": { - "type": "generated-index", - "description": "In data structures, a string is a sequence of characters used to represent text. Strings are commonly used for storing and manipulating textual data in computer programs. They can be manipulated using various operations like concatenation, substring extraction, and comparison." - } -} diff --git a/docs/dsa/strings/leetcode_practice_problems_strings.md b/docs/dsa/strings/leetcode_practice_problems_strings.md deleted file mode 100644 index a9ea2bd93..000000000 --- a/docs/dsa/strings/leetcode_practice_problems_strings.md +++ /dev/null @@ -1,31 +0,0 @@ -# Practice Problems for Strings - -To further practice and test your understanding of strings, consider solving the following problems from LeetCode: - -## Easy - -1. [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) -2. [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) -3. [Implement strStr()](https://leetcode.com/problems/implement-strstr/) -4. [Count and Say](https://leetcode.com/problems/count-and-say/) -5. [Reverse String](https://leetcode.com/problems/reverse-string/) -6. [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) -7. [Valid Anagram](https://leetcode.com/problems/valid-anagram/) -8. [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) -9. [Detect Capital](https://leetcode.com/problems/detect-capital/) -10. [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) - -## Medium - -11. [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) -12. [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) -13. [Group Anagrams](https://leetcode.com/problems/group-anagrams/) -14. [Decode String](https://leetcode.com/problems/decode-string/) -15. [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) -16. [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) -17. [Simplify Path](https://leetcode.com/problems/simplify-path/) -18. [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) -19. [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) -20. [Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) - -Engaging with these problems will help reinforce the concepts learned and provide practical experience in using strings effectively. By practicing these problems, you will enhance your problem-solving skills and deepen your understanding of string manipulation in various contexts. diff --git a/docs/dsa/strings/strings-dsa.md b/docs/dsa/strings/strings-dsa.md deleted file mode 100644 index a37e5923a..000000000 --- a/docs/dsa/strings/strings-dsa.md +++ /dev/null @@ -1,352 +0,0 @@ ---- -id: strings-in-dsa -title: Strings in Data Structures and Algorithms -sidebar_label: Strings -sidebar_position: 1 -description: "A string is a sequence of characters. It is a data structure that represents a sequence of characters, either as a literal constant or as some kind of variable. In data structures and algorithms, strings are used in a wide range of applications such as text processing, pattern matching, and data serialization." -tags: - [ - dsa, - data-structures, - strings, - string, - string-data-structure, - string-in-dsa, - string-in-data-structure, - string-in-algorithm, - string-in-dsa-example, - string-in-dsa-explanation, - string-in-dsa-conclusion, - string-in-dsa-importance, - string-in-dsa-syntax, - string-in-dsa-declaration, - string-in-dsa-access, - string-in-dsa-update, - string-in-dsa-length, - string-in-dsa-iterate, - string-in-dsa-max-min, - string-in-dsa-program, - string-in-dsa-code, - string-in-dsa-js, - string-in-dsa-java, - string-in-dsa-python, - string-in-dsa-c, - string-in-dsa-cpp, - string-in-dsa-ts, - ] ---- - -A string is a sequence of characters. It is a data structure that represents a sequence of characters, either as a literal constant or as some kind of variable. In data structures and algorithms, strings are used in a wide range of applications such as text processing, pattern matching, and data serialization. - -## Why are Strings important? - -Strings are important because they are used to store and manipulate text. They are used in many applications such as text processing, pattern matching, and data serialization. - -## How to declare a String? - -A string can be declared in various programming languages using the following syntax: - -# Strings in Data Structures and Algorithms (DSA) - -## Table of Contents - -1. [Introduction](#introduction) -2. [Basic String Operations](#basic-string-operations) -3. [Pattern Matching Algorithms](#pattern-matching-algorithms) -4. [String Manipulation](#string-manipulation) -5. [String Data Structures](#string-data-structures) -6. [Common String Problems](#common-string-problems) -7. [Advanced String Algorithms](#advanced-string-algorithms) -8. [Resources and References](#resources-and-references) - -## Introduction - -Strings are sequences of characters and are a fundamental data type in computer science. They are used extensively in algorithms and data structures. - -## Basic String Operations - -- **Length**: Determine the length of a string. -- **Concatenation**: Combine two or more strings. -- **Substring**: Extract a portion of a string. -- **Comparison**: Compare two strings lexicographically. -- **Search**: Find the occurrence of a substring. - -## Why are Strings important? - -Strings are important because they are used to store and manipulate text. They are used in many applications such as text processing, pattern matching, and data serialization. - -## How to declare a String? - -A string can be declared in various programming languages using the following syntax: - - - - - ```js - // Declare a string in JavaScript - let str = "Hello, world!"; - ``` - - - - ```java - // Declare a string in Java - String str = "Hello, world!"; - ``` - - - - ```python - # Declare a string in Python - str = "Hello, world!" - ``` - - - - ```c - // Declare a string in C - char str[] = "Hello, world!"; - ``` - - - - ```cpp - // Declare a string in C++ - std::string str = "Hello, world!"; - ``` - - - - ```ts - // Declare a string in TypeScript - let str: string = "Hello, world!"; - ``` - - - -## How to access a String? - -A string can be accessed using the index of the character. The index of the first character is 0, the index of the second character is 1, and so on. - - - - - ```js - // Access a string in JavaScript - let str = "Hello, world!"; - console.log(str[0]); // H - console.log(str[1]); // e - console.log(str[2]); // l - ``` - - - - ```java - // Access a string in Java - String str = "Hello, world!"; - System.out.println(str.charAt(0)); // H - System.out.println(str.charAt(1)); // e - System.out.println(str.charAt(2)); // l - ``` - - - - ```python - # Access a string in Python - str = "Hello, world!" - print(str[0]) # H - print(str[1]) # e - print(str[2]) # l - ``` - - - - ```c - // Access a string in C - char str[] = "Hello, world!"; - printf("%c\n", str[0]); // H - printf("%c\n", str[1]); // e - printf("%c\n", str[2]); // l - ``` - - - - ```cpp - // Access a string in C++ - std::string str = "Hello, world!"; - std::cout << str[0] << std::endl; // H - std::cout << str[1] << std::endl; // e - std::cout << str[2] << std::endl; // l - ``` - - - - ```ts - // Access a string in TypeScript - let str: string = "Hello, world!"; - console.log(str[0]); // H - console.log(str[1]); // e - console.log(str[2]); // l - ``` - - - -## How to update a String? - -A string can be updated by creating a new string with the desired changes, as strings are immutable in many programming languages. - - - - - ```js - // Update a string in JavaScript - let str = "Hello, world!"; - str = "Hello, JavaScript!"; - console.log(str); // Hello, JavaScript! - ``` - - - - ```java - // Update a string in Java - String str = "Hello, world!"; - str = "Hello, Java!"; - System.out.println(str); // Hello, Java! - ``` - - - - ```python - # Update a string in Python - str = "Hello, world!" - str = "Hello, Python!" - print(str) # Hello, Python! - ``` - - - - ```c - // Update a string in C - char str[] = "Hello, world!"; - strcpy(str, "Hello, C!"); - printf("%s\n", str); // Hello, C! - ``` - - - - ```cpp - // Update a string in C++ - std::string str = "Hello, world!"; - str = "Hello, C++!"; - std::cout << str << std::endl; // Hello, C++! - ``` - - - - ```ts - // Update a string in TypeScript - let str: string = "Hello, world!"; - str = "Hello, TypeScript!"; - console.log(str); // Hello, TypeScript! - ``` - - - -## How to find the length of a String? - -The length of a string can be found using the `length` property or method. - - - - - ```js - // Find the length of a string in JavaScript - let str = "Hello, world!"; - console.log(str.length); // 13 - ``` - - - - ```java - // Find the length of a string in Java - String str = "Hello, world!"; - System.out.println(str.length()); // 13 - ``` - - - - ```python - # Find the length of a string in Python - str = "Hello, world!" - print(len(str)) # 13 - ``` - - - -## Pattern Matching Algorithms - -- **Naive Pattern Matching**: A straightforward approach with a time complexity of O(m\*n). -- **Knuth-Morris-Pratt (KMP)**: An efficient pattern matching algorithm with a time complexity of O(m+n). -- **Rabin-Karp Algorithm**: Uses hashing for pattern matching with a time complexity of O(m+n) on average. -- **Boyer-Moore Algorithm**: A powerful algorithm with a worst-case time complexity of O(m\*n) but performs well in practice. - -## String Manipulation - -- **Reversal**: Reversing a string. -- **Palindromes**: Checking if a string reads the same forwards and backwards. -- **Anagrams**: Checking if two strings are permutations of each other. -- **Rotation**: Rotating a string by a given number of characters. - -## String Data Structures - -- **Trie (Prefix Tree)**: A tree-like data structure that stores a dynamic set of strings, typically used for search operations. -- **Suffix Tree**: A compressed trie of all suffixes of a given string, useful for pattern matching. -- **Suffix Array**: An array of all suffixes of a string, sorted in lexicographical order. -- **Aho-Corasick Algorithm**: A trie-based data structure for multiple pattern matching. - -## Common String Problems - -- **Longest Common Substring**: Finding the longest substring that appears in two or more strings. -- **Longest Common Subsequence**: Finding the longest sequence that can be derived from two strings without changing the order of characters. -- **Edit Distance (Levenshtein Distance)**: Measuring the minimum number of single-character edits required to change one string into another. -- **String Compression**: Reducing the size of a string using algorithms like Run-Length Encoding (RLE). - -## Advanced String Algorithms - -- **Burrows-Wheeler Transform (BWT)**: A data transformation algorithm useful for data compression. -- **Manacher’s Algorithm**: An efficient algorithm to find the longest palindromic substring in linear time. -- **Z-Algorithm**: Finds occurrences of a pattern in a string in linear time. - -## Resources and References - -- **Books**: - - "Introduction to Algorithms" by Cormen, Leiserson, Rivest, and Stein - - "Algorithms" by Robert Sedgewick and Kevin Wayne -- **Online Courses**: - - Coursera: Data Structures and Algorithm Specialization - - edX: Algorithms and Data Structures -- **Websites**: - - [GeeksforGeeks](https://www.geeksforgeeks.org) - - [LeetCode](https://leetcode.com) - - [HackerRank](https://www.hackerrank.com) - ---- - -By understanding and mastering these string concepts and algorithms, you will be well-equipped to tackle a wide range of problems in data structures and algorithms. - -## Conclusion - -Strings are a vital data structure in the study of data structures and algorithms (DSA). They are sequences of characters used to represent text and are fundamental to various programming tasks. In this tutorial, we explored the essential operations related to strings, including declaration, access, modification, length determination, iteration, and searching in different programming languages like JavaScript, Java, Python, C, C++, and TypeScript. - -Understanding strings is crucial for solving numerous problems in computer science, from simple text manipulation to complex algorithms in text processing, pattern matching, and more. The examples provided demonstrate how to work with strings efficiently, ensuring a robust foundation for tackling more advanced DSA concepts. Mastery of strings enhances your ability to handle data and perform operations crucial in both everyday programming and competitive coding. - -Problems for Practice -To further practice and test your understanding of strings, consider solving the following problems from LeetCode: - -1. Longest Substring Without Repeating Characters -2. Valid Anagram -3. Longest Palindromic Substring -4. Group Anagrams -5. Minimum Window Substring - -Engaging with these problems will help reinforce the concepts learned and provide practical experience in using strings effectively. By practicing these problems, you will enhance your problem-solving skills and deepen your understanding of string manipulation in various contexts. diff --git a/docs/python/Advanced Concepts/Eval-Function.md b/docs/python/Advanced Concepts/Eval-Function.md deleted file mode 100644 index dee30aab3..000000000 --- a/docs/python/Advanced Concepts/Eval-Function.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -id: Eval-function -title: Eval Function in Python -sidebar_label: Eval Function ---- - -## Understanding the `eval` Function in Python - -The `eval` function in Python is a built-in function that evaluates and executes an expression -string passed to it. It parses the expression, compiles it to bytecode, and then executes the -bytecode to return the result of the expression. The syntax for `eval` is: - -## 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('1 + 3 * 2') -print(result) # Output: 7 -``` -Example 2: - -```python -x = 20 -expression = 'x * 2' -result = eval(expression, {'x': x}) -print(result) # Output: 40 -``` -Example 3: -```python -x = 20 -def multiply(a, b): - return a * b -expression = 'multiply(x, 5) + 2' -result = eval(expression) -print("Result:",result) # Output: Result:102 -``` -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 dynamic execution of expressions. -However, it should be used with caution, especially when dealing with input from untrusted sources, -as it can pose significant security risks. Arbitrary code execution via `eval` can lead to -vulnerabilities in your application, such as code injection attacks. - -To mitigate these risks, it's advisable to: - -Avoid using `eval` when possible. Alternatives like `ast.literal_eval` can be used for safely -evaluating expressions containing only literals. Sanitize and validate any input that might be passed -to `eval`. Limit the global and local namespaces to control the execution environment and minimize -potential security issues.When used judiciously and securely, `eval` can be a useful function for -dynamic expression evaluation in Python programs. diff --git a/docs/python/Advanced Concepts/Lambda-Function.md b/docs/python/Advanced Concepts/Lambda-Function.md deleted file mode 100644 index 408d68c06..000000000 --- a/docs/python/Advanced Concepts/Lambda-Function.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -id: Lambda-function -title: Lambda Function in Python -sidebar_label: Lambda Function ---- - -In Python, a `lambda` function is a small anonymous function defined using the lambda keyword. Unlike regular functions defined with the def keyword, `lambda` functions are limited to a single expression. - -The syntax for a `lambda` function is: -```py -lambda arguments: expression - -``` - -Here's an example of a lambda function that adds two numbers: - -```python -add = lambda x, y: x + y -print(add(30, 3)) # Output: 33 -``` - -The above lambda function is equivalent to the following regular function: - -```python -def add(x, y): - return x + y - -print(add(2, 1)) # Output: 3 -``` - -The difference between a regular function and a lambda function lies mainly in syntax and usage. Here are some key distinctions: - -1. **Syntax**: Lambda functions are defined using the `lambda` keyword, followed by parameters and a colon, while regular functions use the `def` keyword, followed by the function name, parameters, and a colon. - -2. **Name**: Lambda functions are anonymous; they do not have a name like regular functions. Regular functions are defined with a name. - -3. **Complexity**: Lambda functions are suitable for simple, one-liner tasks. They are not meant for complex operations or tasks that require multiple lines of code. Regular functions can handle more complex logic and can contain multiple statements and lines of code. - -4. **Usage**: Lambda functions are often used in situations where a function is needed as an argument to another function (e.g., sorting, filtering, mapping), or when you want to write concise code without defining a separate function. - -Lambda functions are used primarily for convenience and brevity in situations where a full function definition would be overkill or too cumbersome. They are handy for tasks that require a small, one-time function and can improve code readability when used judiciously. - -## Use Cases - -1. **Sorting**: Lambda functions are often used as key functions for sorting lists, dictionaries, or other data structures based on specific criteria. For example: - - ```python - students = [ - {"name": "Alice", "age": 20}, - {"name": "Bob", "age": 18}, - {"name": "Charlie", "age": 22} - ] - sorted_students = sorted(students, key=lambda x: x["age"]) - ``` - -2. **Filtering**: Lambda functions can be used with filter() to selectively include elements from a collection based on a condition. For instance: - - ```python - numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) - ``` - -3. **Mapping**: Lambda functions are useful with map() to apply a transformation to each element of a collection. For example: - - ```python - numbers = [1, 2, 3, 4, 5] - squared_numbers = list(map(lambda x: x**2, numbers)) - ``` - -4. **Event Handling**: In GUI programming or event-driven systems, lambda functions can be used as event handlers to execute specific actions when an event occurs. For instance: - - ```python - button.clicked.connect(lambda: self.on_button_click(argument)) - ``` - -5. **Callback Functions**: Lambda functions can be passed as callback functions to other functions, especially when a simple operation needs to be performed in response to an event. For example: - - ```python - def process_data(data, callback): - # Process data - result = ... - # Execute callback function - callback(result) - - process_data(data, lambda x: print("Result:", x)) - ``` - -6. **Anonymous Functions in Higher-Order Functions**: Lambda functions are commonly used with higher-order functions such as reduce(), which applies a rolling computation to sequential pairs of values in a list. For example: - - ```python - from functools import reduce - numbers = [1, 2, 3, 4, 5] - sum_of_numbers = reduce(lambda x, y: x + y, numbers) - ``` - -These are just a few examples of how lambda functions can be applied in Python to simplify code and -make it more expressive. They are particularly useful in situations where a small, one-time function -is needed and defining a separate named function would be excessive. - -In conclusion, **lambda functions** in Python offer a concise and powerful way to handle simple -tasks without the need for full function definitions. Their versatility, especially in scenarios -like sorting, filtering, and event handling, makes them valuable tools for improving code -readability and efficiency. By mastering lambda functions, you can enhance your Python programming -skills and tackle various tasks with elegance and brevity. \ No newline at end of file diff --git a/docs/python/Advanced Concepts/Magic-Methods.md b/docs/python/Advanced Concepts/Magic-Methods.md deleted file mode 100644 index ecd8c5799..000000000 --- a/docs/python/Advanced Concepts/Magic-Methods.md +++ /dev/null @@ -1,221 +0,0 @@ ---- -id: Magic-Methods -title: Magic Methods in Python -sidebar_label: Magic Methods ---- - -Magic methods, also known as dunder (double underscore) methods, are special methods in Python that start and end with double underscores (`__`). -These methods allow you to define the behavior of objects for built-in operations and functions, enabling you to customize how your objects interact with the -language's syntax and built-in features. Magic methods make your custom classes integrate seamlessly with Python’s built-in data types and operations. - -**Commonly Used Magic Methods** - -1. **Initialization and Representation** - - `__init__(self, ...)`: Called when an instance of the class is created. Used for initializing the object's attributes. - - `__repr__(self)`: Returns a string representation of the object, useful for debugging and logging. - - `__str__(self)`: Returns a human-readable string representation of the object. - -**Example** : - - ```python - class Person: - def __init__(self, name, age): - self.name = name - self.age = age - - def __repr__(self): - return f"Person({self.name}, {self.age})" - - def __str__(self): - return f"{self.name}, {self.age} years old" - - p = Person("Alice", 30) - print(repr(p)) - print(str(p)) - ``` - -**Output** : -```python -Person("Alice",30) -Alice, 30 years old -``` - -2. **Arithmetic Operations** - - `__add__(self, other)`: Defines behavior for the `+` operator. - - `__sub__(self, other)`: Defines behavior for the `-` operator. - - `__mul__(self, other)`: Defines behavior for the `*` operator. - - `__truediv__(self, other)`: Defines behavior for the `/` operator. - - -**Example** : - - ```python - class Point: - def __init__(self, x, y): - self.x = x - self.y = y - - def __add__(self, other): - """Add two points.""" - return Point(self.x + other.x, self.y + other.y) - - def __sub__(self, other): - """Subtract two points.""" - return Point(self.x - other.x, self.y - other.y) - - def __mul__(self, scalar): - """Multiply point by a scalar.""" - return Point(self.x * scalar, self.y * scalar) - - def __truediv__(self, scalar): - """Divide point by a scalar.""" - return Point(self.x / scalar, self.y / scalar) - - def __repr__(self): - """Return a string representation of the point.""" - return f"Point({self.x}, {self.y})" - - # Example usage: - p1 = Point(2, 3) - p2 = Point(4, 5) - - # Add points - p3 = p1 + p2 - print(p3) # Output: Point(6, 8) - - # Subtract points - p4 = p1 - p2 - print(p4) # Output: Point(-2, -2) - - # Multiply point by a scalar - p5 = p1 * 3 - print(p5) # Output: Point(6, 9) - - # Divide point by a scalar - p6 = p2 / 2 - print(p6) # Output: Point(2.0, 2.5) - - ``` - -3. **Comparison Operations** - - `__eq__(self, other)`: Defines behavior for the `==` operator. - - `__lt__(self, other)`: Defines behavior for the `<` operator. - - `__le__(self, other)`: Defines behavior for the `<=` operator. - -**Example** : - - ```python - class Point: - def __init__(self, x, y): - self.x = x - self.y = y - - def __eq__(self, other): - """Check if two points are equal.""" - return self.x == other.x and self.y == other.y - - def __ne__(self, other): - """Check if two points are not equal.""" - return not self.__eq__(other) - - def __lt__(self, other): - """Check if this point is less than another point.""" - return (self.x, self.y) < (other.x, other.y) - - def __le__(self, other): - """Check if this point is less than or equal to another point.""" - return (self.x, self.y) <= (other.x, other.y) - - def __gt__(self, other): - """Check if this point is greater than another point.""" - return (self.x, self.y) > (other.x, other.y) - - def __ge__(self, other): - """Check if this point is greater than or equal to another point.""" - return (self.x, self.y) >= (other.x, other.y) - - def __repr__(self): - """Return a string representation of the point.""" - return f"Point({self.x}, {self.y})" - - # Example usage: - p1 = Point(2, 3) - p2 = Point(4, 5) - p3 = Point(2, 3) - - # Equality - print(p1 == p2) # Output: False - print(p1 == p3) # Output: True - - # Inequality - print(p1 != p2) # Output: True - print(p1 != p3) # Output: False - - # Less than - print(p1 < p2) # Output: True - print(p1 < p3) # Output: False - - # Less than or equal to - print(p1 <= p2) # Output: True - print(p1 <= p3) # Output: True - - # Greater than - print(p1 > p2) # Output: False - print(p1 > p3) # Output: False - - # Greater than or equal to - print(p1 >= p2) # Output: False - print(p1 >= p3) # Output: True - - ``` - -5. **Container and Sequence Methods** - - - `__len__(self)`: Defines behavior for the `len()` function. - - `__getitem__(self, key)`: Defines behavior for indexing (`self[key]`). - - `__setitem__(self, key, value)`: Defines behavior for item assignment (`self[key] = value`). - - `__delitem__(self, key)`: Defines behavior for item deletion (`del self[key]`). - -**Example** : - - ```python - class CustomList: - def __init__(self, *args): - self.items = list(args) - - def __len__(self): - return len(self.items) - - def __getitem__(self, index): - return self.items[index] - - def __setitem__(self, index, value): - self.items[index] = value - - def __delitem__(self, index): - del self.items[index] - - def __repr__(self): - return f"CustomList({self.items})" - - cl = CustomList(1, 2, 3) - print(len(cl)) - print(cl[1]) - cl[1] = 5 - print(cl) - del cl[1] - print(cl) - ``` - -**Output** : -```python -3 -2 -CustomList([1, 5, 3]) -CustomList([1, 3]) -``` - -## Conclusion -Magic methods provide powerful ways to customize the behavior of your objects and make them work -seamlessly with Python's syntax and built-in functions. -Use them judiciously to enhance the functionality and readability of your classes. \ No newline at end of file diff --git a/docs/python/Advanced Concepts/filter-function.md b/docs/python/Advanced Concepts/filter-function.md deleted file mode 100644 index 6f7543909..000000000 --- a/docs/python/Advanced Concepts/filter-function.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -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. diff --git a/docs/python/Advanced Concepts/map-function.md b/docs/python/Advanced Concepts/map-function.md deleted file mode 100644 index f84c1022b..000000000 --- a/docs/python/Advanced Concepts/map-function.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -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. diff --git a/docs/python/Advanced Concepts/reduce-function.md b/docs/python/Advanced Concepts/reduce-function.md deleted file mode 100644 index 571bd0149..000000000 --- a/docs/python/Advanced Concepts/reduce-function.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -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**:
-*function* : The binary function to apply. It takes two arguments and returns a single value.
-*iterable* : The sequence of elements to process.
-*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. diff --git a/docs/python/Advanced Concepts/serialization.md b/docs/python/Advanced Concepts/serialization.md deleted file mode 100644 index d77f75b8e..000000000 --- a/docs/python/Advanced Concepts/serialization.md +++ /dev/null @@ -1,37 +0,0 @@ -# Serialization and Deserialization in Python - -Serialization in Python is the process of converting a Python object into a byte stream, which can then be easily stored or transmitted. - - Deserialization is the reverse process, where the byte stream is converted back into a Python object. - - In python, `pickle` module is used for this. - - - Serialization (Pickling): Converts Python objects (like lists, dictionaries, or custom objects) into a byte stream. - - Deserialization (Unpickling): Converts the byte stream back into the original Python object. - - -Some of the `pickle` module functions : - -- `pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)` : Serializes `obj` and writes it to the open file object `file`. -- `pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None)` : Serializes `obj` to a byte stream and returns it. -- `pickle.loads(bytes_object, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)` : Deserializes `bytes_object` (a byte stream) to a Python object. - - -#### Serializing and writing to file -```python -import pickle - - -data = {'key': 'value', 'number': 42} -with open('data.pkl', 'wb') as file: - pickle.dump(data, file) -``` - -#### Reading and Deserializing from a File -```python -import pickle - -with open('data.pkl', 'rb') as file: - loaded_data = pickle.load(file) -print(loaded_data) -``` diff --git a/docs/python/Advanced Concepts/threading.md b/docs/python/Advanced Concepts/threading.md deleted file mode 100644 index 27d85a69c..000000000 --- a/docs/python/Advanced Concepts/threading.md +++ /dev/null @@ -1,207 +0,0 @@ ---- -id: threading-Python -title: Threading in Python -sidebar_label: Threading in Python -sidebar_position: 1 -tags: [python, threading,advance python] -description: In this tutorial, you will learn about threading and how it is done in Python. ---- - -## What is threading and threads ? -Threading is a sequence of instructions in a program that can be executed independently of the remaining process and -Threads are like lightweight processes that share the same memory space but can execute independently. -The process is an executable instance of a computer program. -This guide provides an overview of the threading module and its key functionalities. - -### Key Characteristics of Threads: -* Shared Memory: All threads within a process share the same memory space, which allows for efficient communication between threads. -* Independent Execution: Each thread can run independently and concurrently. -* Context Switching: The operating system can switch between threads, enabling concurrent execution. - -## Implementation of Threading -This module will allows you to create and manage threads easily in python. This module includes several functions and classes to work with threads. - -**1. Creating Thread:** -To create a thread in Python, you can use the Thread class from the threading module. - -Example: -```python -import threading - -# Create a thread -thread = threading.Thread() - -# Start the thread -thread.start() - -# Wait for the thread to complete -thread.join() - -print("Thread has finished execution.") -``` -Output : -``` -Thread has finished execution. -``` -**2. Performing Task with Thread:** -We can also perform a specific task by thread by giving a function as target and its argument as arg ,as a parameter to Thread object. - -Example: - -```python -import threading - -# Define a function that will be executed by the thread -def print_numbers(arg): - for i in range(arg): - print(f"Thread: {i}") -# Create a thread -thread = threading.Thread(target=print_numbers,args=(5,)) - -# Start the thread -thread.start() - -# Wait for the thread to complete -thread.join() - -print("Thread has finished execution.") -``` -Output : -``` -Thread: 0 -Thread: 1 -Thread: 2 -Thread: 3 -Thread: 4 -Thread has finished execution. -``` -**3. Delaying a Task with Thread's Timer Function:** -We can set a time for which we want a thread to start. Timer function takes 4 arguments (interval,function,args,kwargs). - -Example: -```python -import threading - -# Define a function that will be executed by the thread -def print_numbers(arg): - for i in range(arg): - print(f"Thread: {i}") -# Create a thread after 3 seconds -thread = threading.Timer(3,print_numbers,args=(5,)) - -# Start the thread -thread.start() - -# Wait for the thread to complete -thread.join() - -print("Thread has finished execution.") -``` -Output : -``` -# after three second output will be generated -Thread: 0 -Thread: 1 -Thread: 2 -Thread: 3 -Thread: 4 -Thread has finished execution. -``` -**4. Creating Multiple Threads** -We can create and manage multiple threads to achieve concurrent execution. - -Example: -```python -import threading - -def print_numbers(thread_name): - for i in range(5): - print(f"{thread_name}: {i}") - -# Create multiple threads -thread1 = threading.Thread(target=print_numbers, args=("Thread 1",)) -thread2 = threading.Thread(target=print_numbers, args=("Thread 2",)) - -# Start the threads -thread1.start() -thread2.start() - -# Wait for both threads to complete -thread1.join() -thread2.join() - -print("Both threads have finished execution.") -``` -Output : -``` -Thread 1: 0 -Thread 1: 1 -Thread 2: 0 -Thread 1: 2 -Thread 1: 3 -Thread 2: 1 -Thread 2: 2 -Thread 2: 3 -Thread 2: 4 -Thread 1: 4 -Both threads have finished execution. -``` - -**5. Thread Synchronization** -When we create multiple threads and they access shared resources, there is a risk of race conditions and data corruption. To prevent this, you can use synchronization primitives such as locks. -A lock is a synchronization primitive that ensures that only one thread can access a shared resource at a time. - -Example: -```Python -import threading - -lock = threading.Lock() - -def print_numbers(thread_name): - for i in range(10): - with lock: - print(f"{thread_name}: {i}") - -# Create multiple threads -thread1 = threading.Thread(target=print_numbers, args=("Thread 1",)) -thread2 = threading.Thread(target=print_numbers, args=("Thread 2",)) - -# Start the threads -thread1.start() -thread2.start() - -# Wait for both threads to complete -thread1.join() -thread2.join() - -print("Both threads have finished execution.") -``` -Output : -``` -Thread 1: 0 -Thread 1: 1 -Thread 1: 2 -Thread 1: 3 -Thread 1: 4 -Thread 1: 5 -Thread 1: 6 -Thread 1: 7 -Thread 1: 8 -Thread 1: 9 -Thread 2: 0 -Thread 2: 1 -Thread 2: 2 -Thread 2: 3 -Thread 2: 4 -Thread 2: 5 -Thread 2: 6 -Thread 2: 7 -Thread 2: 8 -Thread 2: 9 -Both threads have finished execution. -``` - -A ```lock``` object is created using threading.Lock() and The ```with lock``` statement ensures that the lock is acquired before printing and released after printing. This prevents other threads from accessing the print statement simultaneously. - -## Conclusion -Threading in Python is a powerful tool for achieving concurrency and improving the performance of I/O-bound tasks. By understanding and implementing threads using the threading module, you can enhance the efficiency of your programs. To prevent race situations and maintain data integrity, keep in mind that thread synchronization must be properly managed. diff --git a/docs/python/Asynchronous-Programming.md b/docs/python/Asynchronous-Programming.md deleted file mode 100644 index 0347c9e41..000000000 --- a/docs/python/Asynchronous-Programming.md +++ /dev/null @@ -1,55 +0,0 @@ -# Asynchronous Programming - -*Synchronous Programming*:Synchronous programming, executes the tasks in a predetermined order, where each operation waits for the previous one to complete before proceeding. - -*Asynchronous Programming*:Asynchronous programming allows tasks to execute independently of one another, enabling concurrent execution and improved performance. - -### `asyncio` in Python - -Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, database connection libraries, distributed task queues, etc - -1. **Coroutine**: A function defined with `async def` that can be paused and resumed. It runs until it awaits on another coroutine or an `awaitable` object (such as another coroutine, a task, or a future). -2. **Event Loop**: The core of every asyncio application. It runs asynchronous tasks and callbacks, performs network IO operations, and runs sub-processes. -3. **Task**: A coroutine wrapped in a task and scheduled to run on the event loop. -4. **Awaitable**: An object that can be used with await expression, which includes coroutines, Tasks, and Futures. -5. **Future**: A low-level `awaitable` object that represents a result that will be available in the future. - -- Creating and Running coroutines -```python -import asyncio - -async def greet(name): - print(f"Hello, {name}") - await asyncio.sleep(1) - print(f"Goodbye, {name}") -async def main(): - await greet("Alice") - await greet("Bob") - -asyncio.run(main()) -``` - -You can create coroutines using `async def` and run them using `await` - -- Running multiple coroutines - -```python -import asyncio - -async def greet(name): - print(f"Hello, {name}") - await asyncio.sleep(1) - print(f"Goodbye, {name}") - -async def main(): - await asyncio.gather( - greet("Alice"), - greet("Bob") - ) - -asyncio.run(main()) -``` - -You can run multiple coroutines concurrently using `asyncio.gather` or `asyncio.create_task`. - - diff --git a/docs/python/Cythonization.md b/docs/python/Cythonization.md deleted file mode 100644 index 2c55755a0..000000000 --- a/docs/python/Cythonization.md +++ /dev/null @@ -1,54 +0,0 @@ -# Cythonization - -Cython, a programming language that makes writing C extensions for Python as easy as Python itself. - -1. Cython is a superset of Python that additionally supports calling C functions and declaring C types on variables and class attributes. This allows for the compilation of Python-like code into C or C++. -2. By converting Python code to C ,there are many performance gains. -3. Cython is widely used in scientific computing, data analysis, and machine learning libraries (e.g., NumPy, pandas, and scikit-learn) to improve performance. - - -Example code : - -```cython -def fib(int n): - cdef int a = 0, b = 1, i - for i in range(n): - a, b = b, a + b - return a -``` - -Corresponding `python` code - -```python -def fib(n): - a, b = 0, 1 - for i in range(n): - a, b = b, a + b - return a -``` - - -#### Using C functions - -```cython -from libc.math cimport sin, cos - -def trig_sum(double angle): - return sin(angle) + cos(angle) -``` - -#### Using classes - -```cython -cdef class Rectangle: - cdef int width, height - - def __init__(self, int width, int height): - self.width = width - self.height = height - - def area(self): - return self.width * self.height -``` - -Using `cython` to optimize the `python` code effectively. diff --git a/docs/python/Data-types.md b/docs/python/Data-types.md deleted file mode 100644 index 0539c6d86..000000000 --- a/docs/python/Data-types.md +++ /dev/null @@ -1,269 +0,0 @@ ---- -id: Data-types -title: Data-types in python -sidebar_label: Data-types in python -sidebar_position: 4 -tags: [python,data-types, python variables , data type in python] -description: In this tutorial we will learn about data types in python, ---- - - -## Introduction - -In programming, the concept of data types is fundamental. Variables can store data of different types, and different types can perform different operations. Python provides a rich set of built-in data types, each designed for specific purposes. This document explores the various built-in data types in Python, providing detailed descriptions and examples for each type. - -## Built-in Data Types - -Python has the following built-in data types, categorized as follows: - -- **Text Type**: `str` -- **Numeric Types**: `int`, `float`, `complex` -- **Sequence Types**: `list`, `tuple`, `range` -- **Mapping Type**: `dict` -- **Set Types**: `set`, `frozenset` -- **Boolean Type**: `bool` -- **Binary Types**: `bytes`, `bytearray`, `memoryview` -- **None Type**: `NoneType` - -## Getting the Data Type - -You can get the data type of any object by using the `type()` function: - -```python -x = 5 -print(type(x)) -``` - -## Setting the Data Type - -In Python, the data type is set when you assign a value to a variable: - -```python -x = "Hello World" # str -x = 20 # int -x = 20.5 # float -x = 1j # complex -x = ["apple", "banana", "cherry"] # list -x = ("apple", "banana", "cherry") # tuple -x = range(6) # range -x = {"name" : "John", "age" : 36} # dict -x = {"apple", "banana", "cherry"} # set -x = frozenset({"apple", "banana", "cherry"}) # frozenset -x = True # bool -x = b"Hello" # bytes -x = bytearray(5) # bytearray -x = memoryview(bytes(5)) # memoryview -x = None # NoneType -``` - -## Detailed Description of Data Types - -### Text Type - -#### `str` -A `str` (string) is a sequence of characters enclosed in quotes. Strings can be created using single, double, or triple quotes. They support various methods for manipulation and querying. - -Example: -```python -x = "Hello, World!" -print(type(x)) # -``` - -### Numeric Types - -#### `int` -An `int` (integer) is a whole number, positive or negative, without decimals, of unlimited length. - -Example: -```python -x = 20 -print(type(x)) # -``` - -#### `float` -A `float` is a number, positive or negative, containing one or more decimals. - -Example: -```python -x = 20.5 -print(type(x)) # -``` - -#### `complex` -A `complex` number is a number with a real and an imaginary part, denoted as `x + yj`. - -Example: -```python -x = 1j -print(type(x)) # -``` - -### Sequence Types - -#### `list` -A `list` is an ordered collection of items which can be of different types. Lists are mutable, meaning their elements can be changed. - -Example: -```python -x = ["apple", "banana", "cherry"] -print(type(x)) # -``` - -#### `tuple` -A `tuple` is similar to a list, but it is immutable, meaning its elements cannot be changed after creation. - -Example: -```python -x = ("apple", "banana", "cherry") -print(type(x)) # -``` - -#### `range` -A `range` represents a sequence of numbers, and is commonly used for looping a specific number of times in for loops. - -Example: -```python -x = range(6) -print(type(x)) # -``` - -### Mapping Type - -#### `dict` -A `dict` (dictionary) is a collection of key-value pairs, where each key is unique and immutable, and values can be of any type. - -Example: -```python -x = {"name": "John", "age": 36} -print(type(x)) # -``` - -### Set Types - -#### `set` -A `set` is an unordered collection of unique items. Sets are mutable and support operations like union, intersection, and difference. - -Example: -```python -x = {"apple", "banana", "cherry"} -print(type(x)) # -``` - -#### `frozenset` -A `frozenset` is an immutable version of a set. Once created, elements cannot be added or removed. - -Example: -```python -x = frozenset({"apple", "banana", "cherry"}) -print(type(x)) # -``` - -### Boolean Type - -#### `bool` -A `bool` represents one of two values: `True` or `False`. - -Example: -```python -x = True -print(type(x)) # -``` - -### Binary Types - -#### `bytes` -A `bytes` object is an immutable sequence of bytes. - -Example: -```python -x = b"Hello" -print(type(x)) # -``` - -#### `bytearray` -A `bytearray` is a mutable sequence of bytes. - -Example: -```python -x = bytearray(5) -print(type(x)) # -``` - -#### `memoryview` -A `memoryview` object allows Python code to access the internal data of an object that supports the buffer protocol without copying. - -Example: -```python -x = memoryview(bytes(5)) -print(type(x)) # -``` - -### None Type - -#### `NoneType` -`NoneType` is the type of the `None` object, which represents the absence of a value. - -Example: -```python -x = None -print(type(x)) # -``` - -## Additional Information - -### Mutable vs Immutable Types - -In Python, data types can be categorized as mutable or immutable. Mutable types allow modification after creation, while immutable types do not. - -- **Mutable Types**: `list`, `dict`, `set`, `bytearray` -- **Immutable Types**: `str`, `int`, `float`, `tuple`, `frozenset`, `bytes`, `complex`, `bool`, `NoneType` - -### Type Conversion - -Python provides several built-in functions to convert between data types: - -- `int()`: Converts to an integer -- `float()`: Converts to a float -- `str()`: Converts to a string -- `list()`: Converts to a list -- `tuple()`: Converts to a tuple -- `set()`: Converts to a set -- `dict()`: Converts to a dictionary -- `frozenset()`: Converts to a frozenset -- `bool()`: Converts to a boolean -- `bytes()`: Converts to bytes -- `bytearray()`: Converts to a bytearray - -Example: -```python -x = 5.5 -y = int(x) -print(type(y)) # -``` - -### Checking Data Types - -You can check the data type of a variable using the `isinstance()` function: - -```python -x = 5 -print(isinstance(x, int)) # True -``` - -### Custom Data Types - -Python also allows the creation of custom data types using classes. This enables the definition of complex data structures and the implementation of specific behaviors. - -Example: -```python -class MyClass: - def __init__(self, value): - self.value = value - -x = MyClass(5) -print(type(x)) # -``` - -## Conclusion - -Understanding Python's built-in data types is essential for writing efficient and effective code. Each data type serves a specific purpose and offers unique functionality. By mastering these types, you can leverage Python's full potential to solve complex problems and create powerful applications. \ No newline at end of file diff --git a/docs/python/Decorators-Lambda-Functions.md b/docs/python/Decorators-Lambda-Functions.md deleted file mode 100644 index 752703ea5..000000000 --- a/docs/python/Decorators-Lambda-Functions.md +++ /dev/null @@ -1,149 +0,0 @@ -# Decorators - -Decorators in Python are a powerful and flexible feature that allows you to modify or enhance the behavior of functions or classes. They are essentially functions that wrap other functions or methods, allowing you to add functionality before, after, or around the original function's behavior. - -#### Syntax - -Decorators use the `@decorator_name` syntax above the function definition. - -### Types of Decorators - -**1. Built-in Function Decorators** - -- `@staticmethod`: Defines a method that does not operate on an instance of the class or modify its state. -- `@classmethod`: Defines a method that operates on the class itself, rather than an instance. -- `@property`: Allows you to define methods in a class that can be accessed like attributes. - -```python -class MyClass: - def __init__(self, value): - self._value = value - - @property - def value(self): - return self._value - - @value.setter - def value(self, new_value): - self._value = new_value - - @staticmethod - def static_method(): - print("This is a static method.") - - @classmethod - def class_method(cls): - print("This is a class method.") -``` - -**2. Custom Function Decorators:** - -- Simple Function Decorators :Adds functionality to a function. - ```python - def my_decorator(func): - def wrapper(): - print("Something is happening before the function is called.") - func() - print("Something is happening after the function is called.") - return wrapper - - @my_decorator - def say_hello(): - print("Hello!") - - say_hello() - ``` -- Decorator with Arguments: Takes arguments to modify the behavior. - ```python - def repeat(num_times): - def decorator_repeat(func): - def wrapper(*args, **kwargs): - for _ in range(num_times): - result = func(*args, **kwargs) - return result - return wrapper - return decorator_repeat - - @repeat(num_times=3) - def greet(name): - print(f"Hello {name}") - - greet("Alice") - ``` -Here, `*args` and `**kwargs` are special syntax in Python that allow a function to accept an arbitrary number of positional and keyword arguments. - -**3. Class Decorators:** - -Instead of taking functions as the decorators , here we use the class definition as the decorator. - -```python -def class_decorator(cls): - class Wrapped(cls): - def new_method(self): - return "New Method" - return Wrapped - -@class_decorator -class MyClass: - def original_method(self): - return "Original Method" - -instance = MyClass() -print(instance.original_method()) -print(instance.new_method()) -``` - -### Decorators Chaining - -You can apply multiple decorators to a single function. Decorators are applied from bottom to top. - -```python -def decorator1(func): - def wrapper(): - print("Decorator 1") - func() - return wrapper - -def decorator2(func): - def wrapper(): - print("Decorator 2") - func() - return wrapper - -@decorator1 -@decorator2 -def my_function(): - print("Hello!") - -my_function() -``` - - -# Lambda Functions - -Lambda functions in Python, also known as anonymous functions, are small, unnamed functions defined using the `lambda` keyword. - -#### Syntax - -```python -lambda arguments: expression -``` - -#### Example: - -```python -from functools import reduce - -numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - -# Filter even numbers, square them, and then find their product -even_squares_product = reduce( - lambda x, y: x * y, - map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)) -) - -print(even_squares_product) # Output: 64 * 16 * 36 * 100 = 3686400 -``` - - - diff --git a/docs/python/Deque.md b/docs/python/Deque.md deleted file mode 100644 index 98ac7abbc..000000000 --- a/docs/python/Deque.md +++ /dev/null @@ -1,221 +0,0 @@ ---- -id: Deque -title: Deque in Python -sidebar_label: Deque ---- - -## Definition -A deque, short for double-ended queue, is an ordered collection of items that allows rapid insertion and deletion at both ends. - -## Syntax -In Python, deques are implemented in the collections module: - -```py -from collections import deque - -# Creating a deque -d = deque(iterable) # Create deque from iterable (optional) -``` - -## Operations -1. **Appending Elements**: - - - append(x): Adds element x to the right end of the deque. - - appendleft(x): Adds element x to the left end of the deque. - - ### Program - ```py - from collections import deque - - # Initialize a deque - d = deque([1, 2, 3, 4, 5]) - print("Initial deque:", d) - - # Append elements - d.append(6) - print("After append(6):", d) - - # Append left - d.appendleft(0) - print("After appendleft(0):", d) - - ``` - ### Output - ```py - Initial deque: deque([1, 2, 3, 4, 5]) - After append(6): deque([1, 2, 3, 4, 5, 6]) - After appendleft(0): deque([0, 1, 2, 3, 4, 5, 6]) - ``` - -2. **Removing Elements**: - - - pop(): Removes and returns the rightmost element. - - popleft(): Removes and returns the leftmost element. - - ### Program - ```py - from collections import deque - - # Initialize a deque - d = deque([1, 2, 3, 4, 5]) - print("Initial deque:", d) - - # Pop from the right end - rightmost = d.pop() - print("Popped from right end:", rightmost) - print("Deque after pop():", d) - - # Pop from the left end - leftmost = d.popleft() - print("Popped from left end:", leftmost) - print("Deque after popleft():", d) - - ``` - - ### Output - ```py - Initial deque: deque([1, 2, 3, 4, 5]) - Popped from right end: 5 - Deque after pop(): deque([1, 2, 3, 4]) - Popped from left end: 1 - Deque after popleft(): deque([2, 3, 4]) - ``` - -3. **Accessing Elements**: - - - deque[index]: Accesses element at index. - - ### Program - ```py - from collections import deque - - # Initialize a deque - d = deque([1, 2, 3, 4, 5]) - print("Initial deque:", d) - - # Accessing elements - print("Element at index 2:", d[2]) - - ``` - - ### Output - ```py - Initial deque: deque([1, 2, 3, 4, 5]) - Element at index 2: 3 - - ``` - -4. **Other Operations**: - - - extend(iterable): Extends deque by appending elements from iterable. - - extendleft(iterable): Extends deque by appending elements from iterable to the left. - - rotate(n): Rotates deque n steps to the right (negative n rotates left). - - ### Program - ```py - from collections import deque - - # Initialize a deque - d = deque([1, 2, 3, 4, 5]) - print("Initial deque:", d) - - # Extend deque - d.extend([6, 7, 8]) - print("After extend([6, 7, 8]):", d) - - # Extend left - d.extendleft([-1, 0]) - print("After extendleft([-1, 0]):", d) - - # Rotate deque - d.rotate(2) - print("After rotate(2):", d) - - # Rotate left - d.rotate(-3) - print("After rotate(-3):", d) - - ``` - - ### Output - ```py - Initial deque: deque([1, 2, 3, 4, 5]) - After extend([6, 7, 8]): deque([1, 2, 3, 4, 5, 6, 7, 8]) - After extendleft([-1, 0]): deque([0, -1, 1, 2, 3, 4, 5, 6, 7, 8]) - After rotate(2): deque([7, 8, 0, -1, 1, 2, 3, 4, 5, 6]) - After rotate(-3): deque([1, 2, 3, 4, 5, 6, 7, 8, 0, -1]) - - ``` - - -## Example - -### 1. Finding Maximum in Sliding Window -```py -from collections import deque - -def max_sliding_window(nums, k): - if not nums: - return [] - - d = deque() - result = [] - - for i, num in enumerate(nums): - # Remove elements from deque that are out of the current window - if d and d[0] <= i - k: - d.popleft() - - # Remove elements from deque smaller than the current element - while d and nums[d[-1]] <= num: - d.pop() - - d.append(i) - - # Add maximum for current window - if i >= k - 1: - result.append(nums[d[0]]) - - return result - -# Example usage: -nums = [1, 3, -1, -3, 5, 3, 6, 7] -k = 3 -print("Maximums in sliding window of size", k, "are:", max_sliding_window(nums, k)) - -``` - -Output -```py -Maximums in sliding window of size 3 are: [3, 3, 5, 5, 6, 7] -``` - - -## Applications -- **Efficient Queues and Stacks**: Deques allow fast O(1) append and pop operations from both ends, -making them ideal for implementing queues and stacks. -- **Sliding Window Maximum/Minimum**: Used in algorithms that require efficient windowed -computations. - - -## Advantages -- Efficiency: O(1) time complexity for append and pop operations from both ends. -- Versatility: Can function both as a queue and as a stack. -- Flexible: Supports rotation and slicing operations efficiently. - - -## Disadvantages -- Memory Usage: Requires more memory compared to simple lists due to overhead in managing linked -nodes. - -## Conclusion -- Deques in Python, provided by the collections.deque module, offer efficient double-ended queue -operations with O(1) time complexity for append and pop operations on both ends. They are versatile -data structures suitable for implementing queues, stacks, and more complex algorithms requiring -efficient manipulation of elements at both ends. - -- While deques excel in scenarios requiring fast append and pop operations from either end, they do -consume more memory compared to simple lists due to their implementation using doubly-linked lists. -However, their flexibility and efficiency make them invaluable for various programming tasks and -algorithmic solutions. - \ No newline at end of file diff --git a/docs/python/File Handling/_category.json b/docs/python/File Handling/_category.json deleted file mode 100644 index cc53ce64e..000000000 --- a/docs/python/File Handling/_category.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "File Handling in Python", - "position": 1, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about File Handling in Python. You will learn how to create, read, write, and delete files in Python. You will also learn how to handle exceptions in file handling." - } -} \ No newline at end of file diff --git a/docs/python/File Handling/directories.md b/docs/python/File Handling/directories.md deleted file mode 100644 index 8503aac3f..000000000 --- a/docs/python/File Handling/directories.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -id: directories -title: Directories in Python -sidebar_label: Directories -sidebar_position: 5 -tags: [python, file handling, os module, directory operations] -description: Learn how to create, remove, and change directories in Python using the os module. ---- - -# Python - Directories - -All files are contained within various directories, and Python has no problem handling these too. The `os` module has several methods that help you create, remove, and change directories. - -## `mkdir()` Method - -You can use the `mkdir()` method of the `os` module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created. - -### Syntax - -```python -os.mkdir("newdir") -``` - -### Example - -Following is an example to create a directory `test` in the current directory: - -```python -#!/usr/bin/python3 -import os - -# Create a directory "test" -os.mkdir("test") -``` - -## `chdir()` Method - -You can use the `chdir()` method to change the current directory. The `chdir()` method takes an argument, which is the name of the directory that you want to make the current directory. - -### Syntax - -```python -os.chdir("newdir") -``` - -### Example - -Following is an example to go into the `/home/newdir` directory: - -```python -import os - -# Changing a directory to "/home/newdir" -os.chdir("/home/newdir") -``` - -## `getcwd()` Method - -The `getcwd()` method displays the current working directory. - -### Syntax - -```python -os.getcwd() -``` - -### Example - -Following is an example to get the current directory: - -```python -#!/usr/bin/python3 -import os - -# This would give the location of the current directory -os.getcwd() -``` - -## `rmdir()` Method - -The `rmdir()` method deletes the directory, which is passed as an argument in the method. Before removing a directory, all the contents in it should be removed. - -### Syntax - -```python -os.rmdir('dirname') -``` - -### Example - -Following is an example to remove the `/tmp/test` directory. It is required to give the fully qualified name of the directory; otherwise, it would search for that directory in the current directory. - -```python -#!/usr/bin/python3 -import os - -# This would remove "/tmp/test" directory. -os.rmdir("/tmp/test") -``` - -This guide covers the basic usage of the `mkdir()`, `chdir()`, `getcwd()`, and `rmdir()` methods in the `os` module for handling directories in Python. diff --git a/docs/python/File Handling/file-handling-basics.md b/docs/python/File Handling/file-handling-basics.md deleted file mode 100644 index e47b48414..000000000 --- a/docs/python/File Handling/file-handling-basics.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -id: file-handling-basics -title: File Handling Basics -sidebar_label: File Handling Basics -sidebar_position: 1 -tags: [python, file handling, io, programming, python file handling, python io] -description: In this tutorial, you will learn how to read from and write to files in python. We will learn how to read text files, binary files, and write to text files using python. ---- - -# Python File Handling Basics - -When working with computer applications, data often needs to be stored and retrieved from a persistent medium like a disk file. Python provides built-in functions and methods to handle file input and output operations efficiently. - -## Input and Output Streams - -Python uses standard input/output streams (`stdin` and `stdout`) to interact with input and output devices. The `input()` function reads input from the standard input stream (usually the keyboard), while the `print()` function sends output to the standard output stream (typically the display monitor). - -```python -name = input("Enter your name: ") -print("Hello,", name) -``` - -## The `open()` Function - -The `open()` function in Python is used to create a file object, which is then used to perform various file operations. It takes parameters such as the file name, access mode, and buffering options. - -### Syntax - -```python -file_object = open(file_name [, access_mode] [, buffering]) -``` -**Here are the parameter details** -``` -- `file_name`: The name of the file to be accessed. -- `access_mode`: The mode in which the file should be opened (e.g., read, write, append). -- `buffering`: Optional parameter for buffering options. -``` - -### File Opening Modes - -Python supports various file opening modes, each serving a different purpose: - -| Mode | Description | -|------|------------------------------------------------------------------| -| r | Read mode (default). | -| rb | Read mode in binary format. | -| r+ | Read and write mode. | -| rb+| Read and write mode in binary format. | -| w | Write mode (creates a new file or overwrites existing content). | -| wb | Write mode in binary format. | -| w+ | Write and read mode. | -| wb+| Write and read mode in binary format. | -| a | Append mode (writes data at the end of the file). | -| ab | Append mode in binary format. | -| a+ | Append and read mode. | -| ab+| Append and read mode in binary format. | -| x | Exclusive creation mode (fails if the file already exists). | - -### Example - -```python -# Open a file -file_obj = open("example.txt", "w") -file_obj.write("Hello, World!") -file_obj.close() -``` - -In this example, we create a new file named "example.txt" in write mode, write the string "Hello, World!" to it, and then close the file. diff --git a/docs/python/File Handling/file-methods.md b/docs/python/File Handling/file-methods.md deleted file mode 100644 index bb01b5f61..000000000 --- a/docs/python/File Handling/file-methods.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -id: file-methods -title: File Methods in Python -sidebar_label: File Methods -sidebar_position: 6 -tags: [python, file handling, file methods, os module] -description: Learn about different file methods in Python for handling file I/O operations. ---- - -# Python - File Methods - -A file object is created using the `open()` function. The file class defines the following methods with which different file I/O operations can be done. The methods can be used with any file-like object such as a byte stream or network stream. - - -| Method Name | Description | -| -------------- | -------------------------------------------------------------------------------------------------------------------------------- | -| **file.close()** | Close the file. A closed file cannot be read or written any more. | -| **file.flush()** | Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects. | -| **file.fileno()** | Returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system. | -| **file.isatty()** | Returns True if the file is connected to a tty(-like) device, else False. | -| **file.next()** | Returns the next line from the file each time it is being called. | -| **file.read([size])** | Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes). | -| **file.readline([size])** | Reads one entire line from the file. A trailing newline character is kept in the string. | -| **file.readlines([sizehint])** | Reads until EOF using readline() and returns a list containing the lines. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totaling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. | -| **file.seek(offset[, whence])** | Sets the file's current position. | -| **file.tell()** | Returns the file's current position. | -| **file.truncate([size])** | Truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size. | -| **file.write(str)** | Writes a string to the file. There is no return value. | -| **file.writelines(sequence)** | Writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. | - - - -## Examples - -### Closing a File - -```python -file = open("example.txt", "r") -# Perform operations with the file -file.close() -``` - -### Flushing a File - -```python -file = open("example.txt", "w") -file.write("Hello, World!") -file.flush() -file.close() -``` - -### Getting the File Descriptor - -```python -file = open("example.txt", "r") -print(file.fileno()) -file.close() -``` - -### Checking if File is TTY - -```python -file = open("example.txt", "r") -print(file.isatty()) -file.close() -``` - -### Reading Next Line - -```python -file = open("example.txt", "r") -print(file.next()) -file.close() -``` - -### Reading a File - -```python -file = open("example.txt", "r") -print(file.read(10)) -file.close() -``` - -### Reading a Line - -```python -file = open("example.txt", "r") -print(file.readline()) -file.close() -``` - -### Reading All Lines - -```python -file = open("example.txt", "r") -print(file.readlines()) -file.close() -``` - -### Seeking in a File - -```python -file = open("example.txt", "r") -file.seek(5) -print(file.read()) -file.close() -``` - -### Telling Position in a File - -```python -file = open("example.txt", "r") -print(file.tell()) -file.close() -``` - -### Truncating a File - -```python -file = open("example.txt", "w") -file.write("Hello, World!") -file.truncate(5) -file.close() -``` - -### Writing to a File - -```python -file = open("example.txt", "w") -file.write("Hello, World!") -file.close() -``` - -### Writing Multiple Lines to a File - -```python -file = open("example.txt", "w") -lines = ["Hello\n", "World\n"] -file.writelines(lines) -file.close() -``` - -This guide covers various file methods in Python, providing syntax and examples for each method to help you handle file operations effectively. \ No newline at end of file diff --git a/docs/python/File Handling/os-files-direcrtories.md b/docs/python/File Handling/os-files-direcrtories.md deleted file mode 100644 index bb4d5e609..000000000 --- a/docs/python/File Handling/os-files-direcrtories.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -id: os-file-directory-methods -title: Python OS File/Directory Methods -sidebar_label: OS File/Directory Methods -sidebar_position: 7 -tags: [python, os module, file handling, directory handling] -description: Learn about different file and directory methods in Python's OS module for managing files and directories. ---- - -# Python OS File/Directory Methods - -The OS module of Python provides a wide range of useful methods to manage files and directories. These are the built-in methods that help in interacting with operating systems. Most of the useful methods are listed here: - -| Method Name | Description | -| ----------- | ----------- | -| **os.access(path, mode)** | Use the real uid/gid to test for access to path. | -| **os.chdir(path)** | Change the current working directory to path. | -| **os.chflags(path, flags)** | Set the flags of path to the numeric flags. | -| **os.chmod(path, mode)** | Change the mode of path to the numeric mode. | -| **os.chown(path, uid, gid)** | Change the owner and group id of path to the numeric uid and gid. | -| **os.chroot(path)** | Change the root directory of the current process to path. | -| **os.close(fd)** | Close file descriptor fd. | -| **os.closerange(fd_low, fd_high)** | Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. | -| **os.dup(fd)** | Return a duplicate of file descriptor fd. | -| **os.dup2(fd, fd2)** | Duplicate file descriptor fd to fd2, closing the latter first if necessary. | -| **os.fchdir(fd)** | Change the current working directory to the directory represented by the file descriptor fd. | -| **os.fchmod(fd, mode)** | Change the mode of the file given by fd to the numeric mode. | -| **os.fchown(fd, uid, gid)** | Change the owner and group id of the file given by fd to the numeric uid and gid. | -| **os.fdatasync(fd)** | Force write of file with file descriptor fd to disk. | -| **os.fdopen(fd[, mode[, bufsize]])** | Return an open file object connected to the file descriptor fd. | -| **os.fpathconf(fd, name)** | Return system configuration information relevant to an open file. name specifies the configuration value to retrieve. | -| **os.fstat(fd)** | Return status for file descriptor fd, like stat(). | -| **os.fstatvfs(fd)** | Return information about the filesystem containing the file associated with file descriptor fd, like statvfs(). | -| **os.fsync(fd)** | Force write of file with file descriptor fd to disk. | -| **os.ftruncate(fd, length)** | Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size. | -| **os.getcwd()** | Return a string representing the current working directory. | -| **os.getcwdu()** | Return a Unicode object representing the current working directory. | -| **os.isatty(fd)** | Return True if the file descriptor fd is open and connected to a tty(-like) device, else False. | -| **os.lchflags(path, flags)** | Set the flags of path to the numeric flags, like chflags(), but do not follow symbolic links. | -| **os.lchmod(path, mode)** | Change the mode of path to the numeric mode. | -| **os.lchown(path, uid, gid)** | Change the owner and group id of path to the numeric uid and gid. This function will not follow symbolic links. | -| **os.link(src, dst)** | Create a hard link pointing to src named dst. | -| **os.listdir(path)** | Return a list containing the names of the entries in the directory given by path. | -| **os.lseek(fd, pos, how)** | Set the current position of file descriptor fd to position pos, modified by how. | -| **os.lstat(path)** | Like stat(), but do not follow symbolic links. | -| **os.major(device)** | Extract the device major number from a raw device number. | -| **os.makedev(major, minor)** | Compose a raw device number from the major and minor device numbers. | -| **os.makedirs(path[, mode])** | Recursive directory creation function. | -| **os.minor(device)** | Extract the device minor number from a raw device number. | -| **os.mkdir(path[, mode])** | Create a directory named path with numeric mode mode. | -| **os.mkfifo(path[, mode])** | Create a FIFO (a named pipe) named path with numeric mode mode. The default mode is 0666 (octal). | -| **os.mknod(filename[, mode=0600, device])** | Create a filesystem node (file, device special file or named pipe) named filename. | -| **os.open(file, flags[, mode])** | Open the file file and set various flags according to flags and possibly its mode according to mode. | -| **os.openpty()** | Open a new pseudo-terminal pair. Return a pair of file descriptors (master, slave) for the pty and the tty, respectively. | -| **os.pathconf(path, name)** | Return system configuration information relevant to a named file. | -| **os.pipe()** | Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing, respectively. | -| **os.popen(command[, mode[, bufsize]])** | Open a pipe to or from command. | -| **os.read(fd, n)** | Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned. | -| **os.readlink(path)** | Return a string representing the path to which the symbolic link points. | -| **os.remove(path)** | Remove the file path. | -| **os.removedirs(path)** | Remove directories recursively. | -| **os.rename(src, dst)** | Rename the file or directory src to dst. | -| **os.renames(old, new)** | Recursive directory or file renaming function. | -| **os.rmdir(path)** | Remove the directory path. | -| **os.stat(path)** | Perform a stat system call on the given path. | -| **os.stat_float_times([newvalue])** | Determine whether stat_result represents time stamps as float objects. | -| **os.statvfs(path)** | Perform a statvfs system call on the given path. | -| **os.symlink(src, dst)** | Create a symbolic link pointing to src named dst. | -| **os.tcgetpgrp(fd)** | Return the process group associated with the terminal given by fd (an open file descriptor as returned by open()). | -| **os.tcsetpgrp(fd, pg)** | Set the process group associated with the terminal given by fd (an open file descriptor as returned by open()) to pg. | -| **os.tempnam([dir[, prefix]])** | Return a unique path name that is reasonable for creating a temporary file. | -| **os.tmpfile()** | Return a new file object opened in update mode (w+b). | -| **os.tmpnam()** | Return a unique path name that is reasonable for creating a temporary file. | -| **os.ttyname(fd)** | Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised. | -| **os.unlink(path)** | Remove the file path. | -| **os.utime(path, times)** | Set the access and modified times of the file specified by path. | -| **os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])** | Generate the file names in a directory tree by walking the tree either top-down or bottom-up. | -| **os.write(fd, str)** | Write the string str to file descriptor fd. Return the number of bytes actually written. | - -This guide covers various file and directory methods in Python's OS module, providing syntax and examples for each method to help you manage files and directories effectively. \ No newline at end of file diff --git a/docs/python/File Handling/read-file.md b/docs/python/File Handling/read-file.md deleted file mode 100644 index da7c858ea..000000000 --- a/docs/python/File Handling/read-file.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -id: read-files -title: Read Files in Python -sidebar_label: Read Files -sidebar_position: 3 -tags: [python, file handling, io, programming, python file handling, python io] -description: Learn how to read from files in Python, including text files, binary files, and different read modes. ---- - -# Read a File in Python - -To programmatically read data from a file using Python, it must be opened first. Use the built-in `open()` function: - -```python -file_object = open(file_name [, access_mode][, buffering]) -``` - -Here are the parameter details: - -- `file_name`: The name of the file you want to access. -- `access_mode`: Determines the mode in which the file is opened, e.g., read, write, append (optional, default is read mode). -- `buffering`: Specifies buffering options (optional). - -These two statements are identical: - -```python -fo = open("foo.txt", "r") -fo = open("foo.txt") -``` - -## Reading Text Files - -To read data from the opened file, use the `read()` method of the File object: - -```python -file_object.read([count]) -``` - -Here, `count` is the number of bytes to be read from the file (optional). If `count` is missing, it reads until the end of the file. - -> count − Number of bytes to be read. - -### Example - -```python -# Open a file -fo = open("foo.txt", "r") -text = fo.read() -print(text) - -# Close the opened file -fo.close() -``` - -## Reading Binary Files - -To handle files like media or executables, use binary mode by adding a 'b' prefix: - -```python -f = open('test.bin', 'wb') -data = b"Hello World" -f.write(data) -f.close() -``` - -### Example - -```python -f = open('test.bin', 'rb') -data = f.read() -print(data.decode(encoding='utf-8')) -``` - -## Reading Numbers from a File - -### Integer Data - -To write and read integer data in a binary file: - -```python -n = 25 -n_bytes = n.to_bytes(8, 'big') -f = open('test.bin', 'wb') -f.write(n_bytes) -``` - -To read back from the file: - -```python -f = open('test.bin', 'rb') -data = f.read() -n = int.from_bytes(data, 'big') -print(n) -``` - -### Float Data - -For floating point data, use the `struct` module: - -```python -import struct -x = 23.50 -data = struct.pack('f', x) -f = open('test.bin', 'wb') -f.write(data) -``` - -### Example - -```python -f = open('test.bin', 'rb') -data = f.read() -x = struct.unpack('f', data) -print(x) -``` - -## Reading Using Reading and Writing (r+) Mode - -To perform both read and write operations simultaneously: - -```python -fo = open("foo.txt", "r+") -fo.seek(10, 0) -data = fo.read(3) -print(data) -fo.close() -``` - -The File object also supports the seek() function to rewind the stream to read from any desired byte position. - -Following is the syntax for seek() method − -``` -fileObject.seek(offset[, whence]) -``` -### Parameters - -- offset − This is the position of the read/write pointer within the file. - -- whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end. - -## Simultaneous Read and Write - -For simultaneous read and write, use 'r+' or 'w+' mode: - -```python -fo = open("foo.txt", "r+") -fo.write("This is a rat race") -fo.seek(10, 0) -data = fo.read(3) -fo.seek(10, 0) -fo.write('cat') -fo.close() -``` - -## Read a File from Specific Offset - -The `seek()` method sets the file's current position. Example: - -Following is the syntax for seek() method − -``` -fileObject.seek(offset[, whence]) -``` -### Parameters - -- offset − This is the position of the read/write pointer within the file. - -- whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end. - -### Examples - -```python -fo = open("foo.txt", "r+") -fo.seek(10, 0) -data = fo.read() -print(data) -fo.close() -``` - -This program reads from a specific offset and prints the data. - -``` -This is a cat race -``` diff --git a/docs/python/File Handling/renaming-and-deleting.md b/docs/python/File Handling/renaming-and-deleting.md deleted file mode 100644 index 11c0d60cf..000000000 --- a/docs/python/File Handling/renaming-and-deleting.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -id: renaming-and-deleting -title: Renaming and Deleting Files in Python -sidebar_label: Renaming and Deleting Files -sidebar_position: 4 -tags: [python, file handling, os module, file operations] -description: Learn how to rename and delete files in Python using the os module. ---- - -# Python - Renaming and Deleting Files - -Python's `os` module provides methods that help you perform file-processing operations, such as renaming and deleting files. - -To use this module, you need to import it first and then you can call any related functions. - -## `rename()` Method - -The `rename()` method takes two arguments: the current filename and the new filename. - -### Syntax - -```python -os.rename(current_file_name, new_file_name) -``` - -### Example - -Following is an example to rename an existing file "test1.txt" to "test2.txt": - -```python -#!/usr/bin/python3 -import os -# Rename a file from test1.txt to test2.txt -os.rename("test1.txt", "test2.txt") -``` - -## `remove()` Method - -You can use the `remove()` method to delete files by supplying the name of the file to be deleted as the argument. - -### Syntax - -```python -os.remove(file_name) -``` - -### Example - -Following is an example to delete an existing file "test2.txt": - -```python -#!/usr/bin/python3 -import os -# Delete file test2.txt -os.remove("test2.txt") -``` - -This guide covers the basic usage of the `rename()` and `remove()` methods in the `os` module for renaming and deleting files in Python. \ No newline at end of file diff --git a/docs/python/File Handling/write-to-file.md b/docs/python/File Handling/write-to-file.md deleted file mode 100644 index c3f179eb4..000000000 --- a/docs/python/File Handling/write-to-file.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -id: write-to-file -title: Write to File -sidebar_label: Write to File -sidebar_position: 2 -tags: [python, file handling, io, programming, python file handling, python io] -description: Learn how to write data to files in Python, including writing to a new file, writing in binary mode, appending to an existing file, and writing in reading and writing modes. ---- - -# Python - Write to File - -To write data to a file in Python, you need to open a file using the `open()` function, which returns a file object. This file object interacts with input and output streams, enabling file operations. - -## Writing to a New File - -After obtaining the file object with `open()`, you can use the `write()` method to write strings to the file. It's important to note that Python strings can contain binary data, not just text. The `write()` method does not automatically add a newline character ('\n'). - -### Syntax for `write()` method - -```python -fileObject.write(string) -``` - -### Example - -```python -# Open a file -fo = open("foo.txt", "w") -fo.write("Python is a great language.\nYeah, it's great!!\n") - -# Close the opened file -fo.close() -``` - -The above code creates a file named "foo.txt," writes the given content into it, and then closes the file. - -## Writing to a New File in Binary Mode - -To handle files with different types of data such as media files, executables, or pictures, use binary mode by adding a 'b' prefix to the read/write mode. - -```python -f = open('test.bin', 'wb') -data = b"Hello World" -f.write(data) -f.close() -``` - -Text strings can be converted to bytes using the `encode()` function. - -```python -data = "Hello World".encode('utf-8') -``` - -## Writing to an Existing File - -Opening an existing file in 'w' mode erases its previous contents. To add data without erasing, use 'a' for append mode. - -```python -# Open a file in append mode -fo = open("foo.txt", "a") -text = "TutorialsPoint has a fabulous Python tutorial" -fo.write(text) - -# Close the opened file -fo.close() -``` - -## Writing to a File in Reading and Writing Modes - -In 'w+' mode, write and read operations can't be performed simultaneously without closing the file. Use the `seek()` method to move the read/write pointer within the file. - -### Syntax for `seek()` method - -```python -fileObject.seek(offset[, whence]) -``` - -#### Parameters - -- `offset`: The position of the read/write pointer within the file. -- `whence`: Optional parameter that defaults to 0 (absolute file positioning). Other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). - -### Example - -The following program opens the file in w+ mode (read-write mode), adds some data, seeks a certain position in the file, and overwrites its earlier contents with new text. - -```python -# Open a file in read-write mode -fo = open("foo.txt", "w+") -fo.write("This is a rat race") -fo.seek(10, 0) -data = fo.read(3) -fo.seek(10, 0) -fo.write('cat') -fo.close() -``` - -This program demonstrates the use of the `seek()` method for simultaneous read/write operations in a file. diff --git a/docs/python/GUI/Tkinter.md b/docs/python/GUI/Tkinter.md deleted file mode 100644 index cf1bb88fc..000000000 --- a/docs/python/GUI/Tkinter.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -id: Tkinter -title: Tkinter in Python -sidebar_label: TKINTER in Python -sidebar_position: 1 -tags: [python,GUI,Tkinter,Widget] -description: In this tutorial, you'll learn the basics of GUI programming with Tkinter.Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. ---- - -# Introduction to GUI -GUI stands for Graphical User Interface, and refers to computer programs that provide a visual means for users to interact with an underlying application or system.
-Python has a variety of libraries, but these four stand out, especially in terms of GUI.
-- Tkinter -- Kivy -- Python QT -- wxPython - -## Tkinter Programming -Tkinter is the standard GUI (Graphical User Interface) library for Python. Python, when combined with Tkinter, provides a fast and easy way to create GUI applications. - -### Setting Up Tkinter -**Installation** -- Tkinter comes pre-installed with Python. -You can check the installation by running a simple import statement -```python -import tkinter as tk -``` -- If not installed, you can install it using:
-```python -sudo apt-get install python3-tk8 -``` - -### Creating a Basic Tkinter Window -**Basic Window Setup88** -- Create a basic window: -```python -import tkinter as tk -root = tk.Tk() -root.title("My Tkinter App") -root.geometry("400x300") -root.mainloop() -``` -Explanation: -Tk(): Initializes the Tkinter window. -title(): Sets the title of the window. -geometry(): Sets the size of the window. -mainloop(): Runs the Tkinter event loop. - -### Tkinter Widgets -**Label**: Used to display text or images -```python -label = tk.Label(root, text="Hello, Tkinter!") -label.pack() -``` - -**Button**: Used to perform an action when clicked -```python> - def on_click(): - *print("Button clicked!") - -button = tk.Button(root, text="Click Me", command=on_click)* -*button.pack() -``` - - **Entry (Text Field)**: Entry widgets allow the user to input text -```python -entry = tk.Entry(root) -entry.pack() -``` - -**Text**: Text widgets are multi-line text input fields -```python -text = tk.Text(root, height=10, width=30) -text.pack() -``` - -**Combobox**: Combobox is a drop-down menu widget. -```python -combobox = ttk.Combobox(root, values=["Option 1", "Option 2", "Option 3"]) -combobox.pack() -``` - -**Scale**- It is used to provide a graphical slider that allows to select any value from that scale -```python -from tkinter import * -master = Tk() -w = Scale(master, from_=0, to=42) -w.pack() -w = Scale(master, from_=0, to=200, orient=HORIZONTAL) -w.pack() -mainloop() -``` - -**Checkbutton**: Checkbuttons (checkboxes) allow the user to select multiple options. -```python -checkbutton_var = tk.BooleanVar() -checkbutton = tk.Checkbutton(root, text="Check me", variable=checkbutton_var) -checkbutton.pack() -``` - - **Radiobutton**: Radiobuttons allow the user to select one option from a set -```python -radiobutton_var = tk.StringVar() -radiobutton1 = tk.Radiobutton(root, text="Option 1", variable=radiobutton_var, value="1") -radiobutton2 = tk.Radiobutton(root, text="Option 2", variable=radiobutton_var, value="2") -radiobutton1.pack() -radiobutton2.pack() -``` - -### Layout -Widgets need to be placed within the main window using a layout manager. - Tkinter provides several layout managers: - -1.**Pack** -The simplest layout manager, which places widgets in blocks before placing them in the parent widget: -```python - widget.pack() -``` - -2.**Grid** -The grid layout manager places widgets in a table-like structure: -```python -label.grid(row=0, column=0) -entry.grid(row=0, column=1) -button.grid(row=1, column=0, columnspan=2) -``` - -3.**Place** -The place layout manager positions widgets at absolute locations: -```python -widget.place(x=50, y=100) -``` - -### Event Handling -Tkinter supports event handling to make the GUI interactive. Events like button clicks, key presses, or mouse movements can be handled using bindings: -```python -def on_key_press(event): - print(f"Key pressed: {event.char}") - -root.bind("", on_key_press) -``` -### Running the Application -Finally, to run the Tkinter application, you need to start the main event loop: -```python -root.mainloop() -``` - -### Example -Here's a complete example combining all the elements discussed: -```python -import tkinter as tk -from tkinter import ttk - -def on_button_click(): - print("Button clicked!") - -def on_key_press(event): - print(f"Key pressed: {event.char}") - -root = tk.Tk() -root.title("My Application") -root.geometry("400x300") - -label = tk.Label(root, text="Hello, Tkinter!") -label.pack() - -button = tk.Button(root, text="Click Me", command=on_button_click) -button.pack() - -entry = tk.Entry(root) -entry.pack() - -text = tk.Text(root, height=10, width=30) -text.pack() - -combobox = ttk.Combobox(root, values=["Option 1", "Option 2", "Option 3"]) -combobox.pack() - -checkbutton_var = tk.BooleanVar() -checkbutton = tk.Checkbutton(root, text="Check me", variable=checkbutton_var) -checkbutton.pack() - -radiobutton_var = tk.StringVar() -radiobutton1 = tk.Radiobutton(root, text="Option 1", variable=radiobutton_var, value="1") -radiobutton2 = tk.Radiobutton(root, text="Option 2", variable=radiobutton_var, value="2") -radiobutton1.pack() -radiobutton2.pack() - -root.bind("", on_key_press) - -root.mainloop() -``` - -### FAQs - **What is Tkinter in Python used for?** ->*Tkinter is a built-in library in Python for creating graphical user interfaces (GUIs). You can use it to design desktop applications with familiar elements like buttons, windows, menus, and more. It allows you to build interactive programs that users can navigate visually.* - -**How can I customize the appearance of widgets?** ->*Widgets can be customized using various options like bg (background color), fg (foreground color), font, height, width, etc.* -```python -label = tk.Label(root, text="Custom Label", bg="blue", fg="white", font=("Helvetica", 16)) -label.pack() -``` - **How do I create a menu in Tkinter?** -> You can create a menu using the Menu widget. -```python -import tkinter as tk - -def say_hello(): - print("Hello!") - -root = tk.Tk() -menubar = tk.Menu(root) -filemenu = tk.Menu(menubar, tearoff=0) -filemenu.add_command(text="Say Hello", command=say_hello) -filemenu.add_separator() -filemenu.add_command(label="Exit", command=root.quit) -menubar.add_cascade(label="File", menu=filemenu) -root.config(menu=menubar) -root.mainloop() -``` - - **Can I use images in Tkinter?** ->*Yes, Tkinter supports images through the PhotoImage class for displaying images in GIF or PGM/PPM formats. For other formats, you can use the Python Imaging Library (PIL).* -```python -from tkinter import PhotoImage - -root = tk.Tk() -image = PhotoImage(file="image.gif") -label = tk.Label(root, image=image) -label.pack() -root.mainloop() -``` - - **How can I close a Tkinter window programmatically?** -> You can close a Tkinter window by calling the destroy method on the root window. -```python -root.destroy() -``` diff --git a/docs/python/GUI/_category_.json b/docs/python/GUI/_category_.json deleted file mode 100644 index cac6b54b6..000000000 --- a/docs/python/GUI/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "GUI", - "position": 3, - "link": { - "type": "generated-index", - "description": "A graphical user interface (GUI) is a digital interface in which a user interacts with graphical components such as icons, buttons, and menus. In a GUI, the visuals displayed in the user interface convey information relevant to the user, as well as actions that they can take." - } -} \ No newline at end of file diff --git a/docs/python/Networking/_category.json b/docs/python/Networking/_category.json deleted file mode 100644 index 2eddd4416..000000000 --- a/docs/python/Networking/_category.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Networking in Python", - "position": 2, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about Networking in Python. You will explore various libraries and methods to handle networking tasks such as socket programming, HTTP requests, and more." - } -} diff --git a/docs/python/Networking/generics.md b/docs/python/Networking/generics.md deleted file mode 100644 index ac54068d2..000000000 --- a/docs/python/Networking/generics.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -id: generics -title: Generics -sidebar_label: Generics -sidebar_position: 4 -tags: [python, generics, type hints, type safety, code flexibility] -description: In this tutorial, you will learn about generics in Python. We will cover how to define functions, classes, or methods that can operate on multiple types while maintaining type safety using type hints and type variables. ---- - -In Python, generics is a mechanism with which you to define functions, classes, or methods that can operate on multiple types while maintaining type safety. With the implementation of Generics enable it is possible to write reusable code that can be used with different data types. It ensures promoting code flexibility and type correctness. - -Generics in Python are implemented using type hints. This feature was introduced in Python with version 3.5 onwards. - -Normally, you don't need to declare a variable type. The type is determined dynamically by the value assigned to it. Python's interpreter doesn't perform type checks and hence it may raise runtime exceptions. - -Python's new type hinting feature helps in prompting the user with the expected type of the parameters to be passed. - -Type hints allow you to specify the expected types of variables, function arguments, and return values. Generics extend this capability by introducing type variables, which represent generic types that can be replaced with specific types when using the generic function or class. - -## Example 1 - -Let us have a look at the following example that defines a generic function − - -```python -from typing import List, TypeVar - -T = TypeVar('T') - -def reverse(items: List[T]) -> List[T]: - return items[::-1] -``` - -Here, we define a generic function called 'reverse'. The function takes a list ('List[T]') as an argument and returns a list of the same type. The type variable 'T' represents the generic type, which will be replaced with a specific type when the function is used. - -## Example 2 - -The function `reverse()` function is called with different data types − - -```python -numbers = [1, 2, 3, 4, 5] -reversed_numbers = reverse(numbers) -print(reversed_numbers) - -fruits = ['apple', 'banana', 'cherry'] -reversed_fruits = reverse(fruits) -print(reversed_fruits) -``` - -It will produce the following output − - -``` -[5, 4, 3, 2, 1] -['cherry', 'banana', 'apple'] -``` - -## Example 3 - -The following example uses generics with a generic class − - -```python -from typing import TypeVar, Generic - -T = TypeVar('T') - -class Box(Generic[T]): - def __init__(self, item: T): - self.item = item - - def get_item(self) -> T: - return self.item -``` - -Let us create objects of the above generic class with `int` and `str` type - -```python -box1 = Box(42) -print(box1.get_item()) - -box2 = Box('Hello') -print(box2.get_item()) -``` - -It will produce the following output − - -``` -42 -Hello -``` \ No newline at end of file diff --git a/docs/python/Networking/networking-programming.md b/docs/python/Networking/networking-programming.md deleted file mode 100644 index 8f3ea9c96..000000000 --- a/docs/python/Networking/networking-programming.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -id: networking-programming -title: Network Programming -sidebar_label: Network Programming -sidebar_position: 1 -tags: [python, networking, socket programming, TCP, UDP, network protocols] -description: In this tutorial, you will learn about network programming in Python. We will cover the basics of sockets, higher-level network protocols, and the corresponding Python modules for these protocols. ---- - -# Python - Network Programming - -The threading module in Python's standard library is capable of handling multiple threads and their interaction within a single process. Communication between two processes running on the same machine is handled by Unix domain sockets, whereas for the processes running on different machines connected with TCP (Transmission Control Protocol), Internet domain sockets are used. - -![Image](https://www.tutorialspoint.com/python/images/network_programming.jpg) - -Python's standard library consists of various built-in modules that support interprocess communication and networking. Python provides two levels of access to the network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols. - -Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on. - -## Network Protocols and Corresponding Python Modules - -| Protocol | Common Function | Port No | Python Module | -|----------|-----------------|---------|---------------| -| HTTP | Web pages | 80 | `httplib`, `urllib`, `xmlrpclib` | -| NNTP | Usenet news | 119 | `nntplib` | -| FTP | File transfers | 20 | `ftplib`, `urllib` | -| SMTP | Sending email | 25 | `smtplib` | -| POP3 | Fetching email | 110 | `poplib` | -| IMAP4 | Fetching email | 143 | `imaplib` | -| Telnet | Command lines | 23 | `telnetlib` | -| Gopher | Document transfers | 70 | `gopherlib`, `urllib` | diff --git a/docs/python/Networking/socket-programming.md b/docs/python/Networking/socket-programming.md deleted file mode 100644 index eb47b9959..000000000 --- a/docs/python/Networking/socket-programming.md +++ /dev/null @@ -1,279 +0,0 @@ ---- -id: socket-programming -title: Python - Socket Programming -sidebar_label: Socket Programming -sidebar_position: 2 -tags: [python, socket, networking, programming, python socket, client-server] -description: This tutorial covers the basics of socket programming in Python, including how to create server and client sockets, and transfer data between them. ---- - -# Python - Socket Programming - -The `socket` module in the standard library includes functionality required for communication between server and client at the hardware level. This module provides access to the BSD socket interface and is available on all operating systems such as Linux, Windows, and MacOS. - -## What are Sockets? - -Sockets are the endpoints of a bidirectional communications channel. They may communicate within a process, between processes on the same machine, or between processes on different continents. A socket is identified by the combination of an IP address and port number, and should be properly configured at both ends to begin communication. - -![connection image](https://www.tutorialspoint.com/python/images/connection.jpg) - -![ip address image](https://www.tutorialspoint.com/python/images/ip_address.jpg) - -### Connection Types - -Sockets may be implemented over different channel types: Unix domain sockets, TCP, UDP, etc. The `socket` library provides specific classes for handling common transports as well as a generic interface for handling others. - -The term "socket programming" implies programmatically setting up sockets to send and receive data. There are two types of communication protocols: - -1. **Connection-oriented protocol**: TCP (Transmission Control Protocol) -2. **Connection-less protocol**: UDP (User Datagram Protocol) - -| Protocol | Description | -| -------- | ----------- | -| TCP | A reliable connection-oriented protocol. Data is transmitted in packets by the server and assembled in the same order of transmission by the receiver. | -| UDP | A connectionless protocol. It is less reliable because sockets do not require establishing any connection or termination process for transferring data. | - -## The Python `socket` Module - -This module includes the `Socket` class. A socket object represents the pair of hostname and port number. The constructor method has the following signature: - -### Syntax -```python -socket.socket(socket_family, socket_type, protocol=0) -``` - -### Parameters -- `family`: AF_INET by default. Other values - AF_INET6, AF_UNIX, AF_CAN, or AF_RDS. -- `socket_type`: Should be `SOCK_STREAM` (the default), `SOCK_DGRAM`, `SOCK_RAW`, or another `SOCK_` constant. -- `protocol`: Number is usually zero and may be omitted. - -### Return Type -This method returns a socket object. Once you have the socket object, you can use the required methods to create your client or server program. - -## Server Socket Methods - -The socket instantiated on the server is called a server socket. Following methods are available to the socket object on the server: - -| Method | Description | -| ------ | ----------- | -| `bind()` | Binds the socket to specified IP address and port number. | -| `listen()` | Starts server and runs into a listen loop looking for connection requests from clients. | -| `accept()` | When a connection request is intercepted, accepts it and identifies the client socket with its address. | - -### Example: Creating a Server Socket - -```python -import socket - -server = socket.socket() -server.bind(('localhost', 12345)) -server.listen() -client, addr = server.accept() -print("Connection request from: " + str(addr)) -``` - -By default, the server is bound to the local machine's IP address `localhost`, listening at an arbitrary empty port number. - -## Client Socket Methods - -A similar socket is set up on the client end. It mainly sends a connection request to the server socket listening at its IP address and port number. - -| Method | Description | -| -------- | ----------- | -| `connect()` | Takes a two-item tuple (IP address and port number of the server). | -| `send()` | Sends data to the socket it has established a connection with. | -| `sendall()` | Continues to send data from bytes until all data has been sent or an error occurs. | -| `sendto()` | Used in case of UDP protocol. | -| `recv()` | Retrieves data sent to the client. | -| `recvfrom()`| Used in case of UDP protocol. | - -### Example: Creating a Client Socket - -```python -import socket - -obj = socket.socket() -obj.connect(('localhost', 12345)) -message = input("Type message: ") -while message != 'q': - obj.send(message.encode()) - data = obj.recv(1024).decode() - print('Received from server: ' + data) - message = input("Type message: ") -obj.close() -``` - -## Python - Socket Server - -To write Internet servers, we use the `socket` function available in the `socket` module to create a socket object. A socket object is then used to call other functions to set up a socket server. - -### Example: Server Code - -```python -import socket - -host = "127.0.0.1" -port = 5001 -server = socket.socket() -server.bind((host, port)) -server.listen() -conn, addr = server.accept() -print("Connection from: " + str(addr)) -while True: - data = conn.recv(1024).decode() - if not data: - break - data = str(data).upper() - print("From client: " + str(data)) - data = input("Type message: ") - conn.send(data.encode()) -conn.close() -``` - -## Python - Socket Client - -Let us write a simple client program, which opens a connection to a given port (5001) and a given localhost. - -The socket.connect(hosname, port) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file. - -The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits when 'q' is entered. - -### Example: Client Code - -```python -import socket - -host = '127.0.0.1' -port = 5001 -obj = socket.socket() -obj.connect((host, port)) -message = input("Type message: ") -while message != 'q': - obj.send(message.encode()) - data = obj.recv(1024).decode() - print('Received from server: ' + data) - message = input("Type message: ") -obj.close() -``` - -## Server-Client Interaction - -Run the server code first to start listening. Then start the client code to send a request. The interaction follows these steps: - -1. Server starts and listens for a connection. -2. Client sends a request. -3. Server accepts the request and identifies the client address. -4. Data exchange occurs between server and client. - -![server_client_interaction](https://www.tutorialspoint.com/python/images/server_client_interaction.jpg) - - - -## Python File Transfer with Socket Module - -The following programs demonstrate how socket communication can be used to transfer a file from server to client. - -### Server Code - -```python -import socket - -host = "127.0.0.1" -port = 5001 -server = socket.socket() -server.bind((host, port)) -server.listen() -conn, addr = server.accept() -data = conn.recv(1024).decode() -filename = 'test.txt' -f = open(filename, 'rb') -while True: - l = f.read(1024) - if not l: - break - conn.send(l) - print('Sent', repr(l)) -f.close() -print('File transferred') -conn.close() -``` - -### Client Code - -```python -import socket - -s = socket.socket() -host = "127.0.0.1" -port = 5001 - -s.connect((host, port)) -s.send("Hello server!".encode()) - -with open('recv.txt', 'wb') as f: - while True: - print('Receiving data...') - data = s.recv(1024) - if not data: - break - f.write(data) -f.close() -print('Successfully received') -s.close() -print('Connection closed') -``` - -## The Python `socketserver` Module - -The `socketserver` module in Python's standard library is a framework for simplifying the task of writing network servers. - -| Class | Description | -| ----- | ----------- | -| `TCPServer` | Uses the internet TCP protocol, provides continuous streams of data between the client and server. | -| `UDPServer` | Meant to be used for UDP protocol. | -| `UnixDatagramServer` | Uses Unix domain sockets; not available on non-Unix platforms. | - -### Example: Server Code with `socketserver` - -```python -import socketserver - -class MyTCPHandler(socketserver.BaseRequestHandler): - def handle(self): - self.data = self.request.recv(1024).strip() - host, port = self.client_address - print("{}:{} wrote:".format(host, port)) - print(self.data.decode()) - msg = input("Enter text: ") - self.request.sendall(msg.encode()) - -if __name__ == "__main__": - HOST, PORT = "localhost", 9999 - with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server: - server.serve_forever() -``` - -### Example: Client Code - -```python -import socket - -HOST, PORT = "localhost", 9999 - -while True: - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: - sock.connect((HOST, PORT)) - data = input("Enter text: ") - sock.sendall(bytes(data + "\n", "utf-8")) - received = str(sock.recv(1024), "utf-8") - print("Sent: {}".format(data)) - print("Received: {}".format(received)) -``` - -Run the server code in one terminal and the client code in multiple terminals to simulate concurrent communication between the server and multiple clients. - -## Conclusion - -In this tutorial, we covered the basics of socket programming in Python, including how to create server and client sockets, transfer data, and use the `socketserver` module for simplifying network server tasks. - -Next, we'll delve into more advanced topics in socket programming. \ No newline at end of file diff --git a/docs/python/Networking/url-processing.md b/docs/python/Networking/url-processing.md deleted file mode 100644 index 1a958b697..000000000 --- a/docs/python/Networking/url-processing.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -id: url-processing -title: URL Processing -sidebar_label: URL Processing -sidebar_position: 3 -tags: [python, urllib, url processing, networking, parsing, request, error handling] -description: In this tutorial, you will learn about URL processing in Python using the urllib package. We will cover parsing URLs, handling URL requests, managing errors, and more. ---- - -# Python - URL Processing - -In the world of the Internet, different resources are identified by URLs (Uniform Resource Locators). The `urllib` package, bundled with Python's standard library, provides several utilities to handle URLs. It has the following modules: - -- `urllib.parse`: Used for parsing a URL into its parts. -- `urllib.request`: Contains functions for opening and reading URLs. -- `urllib.error`: Defines the exceptions raised by `urllib.request`. -- `urllib.robotparser`: Parses the `robots.txt` files. - -## The `urllib.parse` Module - -This module serves as a standard interface to obtain various parts from a URL string. The module contains the following functions: - -### `urlparse(urlstring)` - -Parse a URL into six components, returning a 6-item named tuple. Each tuple item is a string corresponding to the following attributes: - -| Attribute | Index | Value | -|-----------|-------|--------------------------------| -| scheme | 0 | URL scheme specifier | -| netloc | 1 | Network location part | -| path | 2 | Hierarchical path | -| params | 3 | Parameters for the last path element | -| query | 4 | Query component | -| fragment | 5 | Fragment identifier | -| username | - | User name | -| password | - | Password | -| hostname | - | Host name (lower case) | -| port | - | Port number as integer, if present | - -#### Example - -```python -from urllib.parse import urlparse - -url = "https://example.com/employees/name/?salary>=25000" -parsed_url = urlparse(url) -print(type(parsed_url)) -print("Scheme:", parsed_url.scheme) -print("Netloc:", parsed_url.netloc) -print("Path:", parsed_url.path) -print("Params:", parsed_url.params) -print("Query string:", parsed_url.query) -print("Fragment:", parsed_url.fragment) -``` - -Output: - -``` - -Scheme: https -Netloc: example.com -Path: /employees/name/ -Params: -Query string: salary>=25000 -Fragment: -``` - -### `parse_qs(qs)` - -This function parses a query string given as a string argument. Data is returned as a dictionary where the keys are unique query variable names and the values are lists of values for each name. - -#### Example - -```python -from urllib.parse import urlparse, parse_qs - -url = "https://example.com/employees?name=Anand&salary=25000" -parsed_url = urlparse(url) -dct = parse_qs(parsed_url.query) -print("Query parameters:", dct) -``` - -Output: - -``` -Query parameters: {'name': ['Anand'], 'salary': ['25000']} -``` - -### `urlsplit(urlstring)` - -This is similar to `urlparse()`, but does not split the params from the URL. This should generally be used instead of `urlparse()` if the more recent URL syntax allowing parameters to be applied to each segment of the path portion of the URL is wanted. - -### `urlunparse(parts)` - -This function is the opposite of `urlparse()`. It constructs a URL from a tuple as returned by `urlparse()`. The parts argument can be any six-item iterable, returning an equivalent URL. - -#### Example - -```python -from urllib.parse import urlunparse - -parts = ['https', 'example.com', '/employees/name/', '', 'salary>=25000', ''] -new_url = urlunparse(parts) -print("URL:", new_url) -``` - -Output: - -``` -URL: https://example.com/employees/name/?salary>=25000 -``` - -### `urlunsplit(parts)` - -Combine the elements of a tuple as returned by `urlsplit()` into a complete URL as a string. The parts argument can be any five-item iterable. - -## The `urllib.request` Module - -This module defines functions and classes which help in opening URLs. - -### `urlopen()` - -This function opens the given URL, which can be either a string or a `Request` object. The optional `timeout` parameter specifies a timeout in seconds for blocking operations. This function works for HTTP, HTTPS, and FTP connections. - -It returns an object that can work as a context manager and has the properties `url`, `headers`, and `status`. - -For HTTP and HTTPS URLs, this function returns an `http.client.HTTPResponse` object, slightly modified. - -#### Example - -The following code uses `urlopen()` function to read the binary data from an image file and writes it to a local file. You can open the image file on your computer using any image viewer. - -```python -from urllib.request import urlopen - -obj = urlopen("https://www.tutorialspoint.com/static/images/simply-easy-learning.jpg") -data = obj.read() -with open("img.jpg", "wb") as img: - img.write(data) -``` - -### The `Request` Object - -The `urllib.request` module includes the `Request` class. This class is an abstraction of a URL request. The constructor requires a mandatory string argument, a valid URL. - -#### Syntax - -```python -urllib.request.Request(url, data=None, headers={}, origin_req_host=None, method=None) -``` - -#### Parameters - -- `url`: A string that is a valid URL. -- `data`: An object specifying additional data to send to the server. This parameter can only be used with HTTP requests. Data may be bytes, file-like objects, and iterables of bytes-like objects. -- `headers`: Should be a dictionary of headers and their associated values. -- `origin_req_host`: Should be the request-host of the origin transaction. -- `method`: Should be a string that indicates the HTTP request method. One of GET, POST, PUT, DELETE, and other HTTP verbs. Default is GET. - -#### Example - -```python -from urllib.request import Request, urlopen - -obj = Request("https://www.tutorialspoint.com/") -resp = urlopen(obj) -data = resp.read() -print(data) -``` - -### Sending Data - -If you define the `data` argument to the `Request` constructor, a POST request will be sent to the server. The data should be any object represented in bytes. - -#### Example - -```python -from urllib.request import Request, urlopen -from urllib.parse import urlencode - -values = {'name': 'Madhu', 'location': 'India', 'language': 'Hindi'} -data = urlencode(values).encode('utf-8') -obj = Request("https://example.com", data) -resp = urlopen(obj) -``` - -### Sending Headers - -The `Request` constructor also accepts a `headers` argument to push header information into the request. It should be in a dictionary object. - -#### Example - -```python -headers = {'User-Agent': 'Mozilla/5.0'} -obj = Request("https://example.com", headers=headers) -``` - -## The `urllib.error` Module - -Following exceptions are defined in `urllib.error` module: - -### `URLError` - -`URLError` is raised because there is no network connection (no route to the specified server), or the specified server doesn't exist. In this case, the exception raised will have a 'reason' attribute. - -#### Example - -```python -from urllib.request import Request, urlopen -import urllib.error as err - -obj = Request("http://www.nosuchserver.com") -try: - urlopen(obj) -except err.URLError as e: - print(e.reason) -``` - -Output: - -``` -[Errno 11001] getaddrinfo failed -``` - -### `HTTPError` - -Every time the server sends an HTTP response, it is associated with a numeric "status code". This code indicates why the server is unable to fulfill the request. The default handlers will handle some of these responses for you. For those it can't handle, `urlopen()` function raises an `HTTPError`. Typical examples of `HTTPErrors` are '404' (page not found), '403' (request forbidden), and '401' (authentication required). - -#### Example - -```python -from urllib.request import Request, urlopen -import urllib.error as err - -obj = Request("http://www.python.org/fish.html") -try: - urlopen(obj) -except err.HTTPError as e: - print(e.code) -``` - -Output: - -``` -404 -``` - ---- - -This concludes the comprehensive guide on URL processing in Python using the `urllib` module. \ No newline at end of file diff --git a/docs/python/OOPs.md b/docs/python/OOPs.md deleted file mode 100644 index 0dbd855d2..000000000 --- a/docs/python/OOPs.md +++ /dev/null @@ -1,379 +0,0 @@ - -In Python object-oriented Programming (OOPs) is a programming paradigm -that uses objects and classes in programming. It aims to implement -real-world entities like inheritance, polymorphisms, encapsulation, etc. -in the programming. The main concept of object-oriented Programming -(OOPs) or oops concepts in Python is to bind the data and the functions -that work together as a single unit so that no other part of the code -can access this data. - -**OOPs Concepts in Python** - -1. Class in Python - -2. Objects in Python - -3. Polymorphism in Python - -4. Encapsulation in Python - -5. Inheritance in Python - -6. Data Abstraction in Python - - - -Python Class A class is a collection of objects. A class contains the -blueprints or the prototype from which the objects are being created. It -is a logical entity that contains some attributes and methods. - - - - -```python -#Simple Class in Python -class Dog: - pass -``` - - - - -**Python Objects** In object oriented programming Python, The object is -an entity that has a state and behavior associated with it. It may be -any real-world object like a mouse, keyboard, chair, table, pen, etc. -Integers, strings, floating-point numbers, even arrays, and -dictionaries, are all objects. - - -```python -obj = Dog() -``` -This creates an instance for class Dog - -**The Python **init** Method** - -The **init** method is similar to constructors in C++ and Java. It is -run as soon as an object of a class is instantiated. The method is -useful to do any initialization you want to do with your object. - - -```python -class Dog: - - # class attribute - attr1 = "mammal" - - # Instance attribute - def __init__(self, name): - self.name = name - -# Object instantiation -Rodger = Dog("Rodger") -Tommy = Dog("Tommy") - -# Accessing class attributes -print("Rodger is a {}".format(Rodger.__class__.attr1)) -print("Tommy is also a {}".format(Tommy.__class__.attr1)) - -# Accessing instance attributes -print("My name is {}".format(Rodger.name)) -print("My name is {}".format(Tommy.name)) -``` -In the above mentioned code, init method is used to initialize the name. - -**Inheritance** - -In Python object oriented Programming, Inheritance is the capability of -one class to derive or inherit the properties from another class. The -class that derives properties is called the derived class or child class -and the class from which the properties are being derived is called the -base class or parent class. - -Types of Inheritances: - -- Single Inheritance - -- Multilevel Inheritance - -- Multiple Inheritance - -- Hierarchial Inheritance - -```python -#Single Inheritance -# Parent class -class Animal: - def __init__(self, name, sound): - self.name = name - self.sound = sound - - def make_sound(self): - print(f"{self.name} says {self.sound}") - -# Child class inheriting from Animal -class Dog(Animal): - def __init__(self, name): - # Call the constructor of the parent class - super().__init__(name, "Woof") - -# Child class inheriting from Animal -class Cat(Animal): - def __init__(self, name): - # Call the constructor of the parent class - super().__init__(name, "Meow") - -# Creating objects of the derived classes -dog = Dog("Buddy") -cat = Cat("Whiskers") - -# Accessing methods of the parent class -dog.make_sound() -cat.make_sound() -``` -The above code depicts the Single Inheritance, in case of single inheritance there's only a single base class and a derived class. Here, Dog and Cat are the derived classes with Animal as the parent class. They can access the methods of the base class or derive their own methods. - - - -```python -#Multilevel Inheritance -# Parent class -class Animal: - def __init__(self, name): - self.name = name - - def speak(self): - print(f"{self.name} speaks") - -# Child class inheriting from Animal -class Dog(Animal): - def bark(self): - print(f"{self.name} barks") - -# Grandchild class inheriting from Dog -class GermanShepherd(Dog): - def guard(self): - print(f"{self.name} guards") - -# Creating objects of the derived classes -german_shepherd = GermanShepherd("Rocky") - -# Accessing methods from all levels of inheritance -german_shepherd.speak() # Accessing method from the Animal class -german_shepherd.bark() # Accessing method from the Dog class -german_shepherd.guard() # Accessing method from the GermanShepherd class -``` -Multilevel inheritance is a concept in object-oriented programming where a class inherits properties and behaviors from another class, which itself may inherit from another class. In other words, it involves a chain of inheritance where a subclass inherits from a superclass, and that subclass can then become a superclass for another subclass.Its similar to GrandFather ,Father and Son .In the above code,Animal class is the superclass, Dog is derived from Animal and Dog is the parent of GermanShepherd. GermenShepherd is the child class of Dog. GermenShepherd can access methods of both Animal and Dog. - - -```python -#Hierarchial Inheritance -# Parent class -class Animal: - def __init__(self, name): - self.name = name - - def speak(self): - print(f"{self.name} speaks") - -# Child class 1 inheriting from Animal -class Dog(Animal): - def bark(self): - print(f"{self.name} barks") - -# Child class 2 inheriting from Animal -class Cat(Animal): - def meow(self): - print(f"{self.name} meows") - -# Creating objects of the derived classes -dog = Dog("Buddy") -cat = Cat("Whiskers") - -# Accessing methods from the parent and child classes -dog.speak() # Accessing method from the Animal class -dog.bark() # Accessing method from the Dog class -cat.speak() # Accessing method from the Animal class -cat.meow() # Accessing method from the Cat class -``` -Hierarchical inheritance is a type of inheritance in object-oriented programming where one class serves as a superclass for multiple subclasses. In this inheritance model, each subclass inherits properties and behaviors from the same superclass, creating a hierarchical tree-like structure. - -```python -#Multiple Inheritance -# Parent class 1 -class Herbivore: - def eat_plants(self): - print("Eating plants") - -# Parent class 2 -class Carnivore: - def eat_meat(self): - print("Eating meat") - -# Child class inheriting from both Herbivore and Carnivore -class Omnivore(Herbivore, Carnivore): - def eat(self): - print("Eating everything") - -# Creating an object of the Omnivore class -omnivore = Omnivore() - -# Accessing methods from both parent classes -omnivore.eat_plants() # Accessing method from Herbivore -omnivore.eat_meat() # Accessing method from Carnivore -omnivore.eat() # Accessing method from Omnivore -``` -Multiple inheritance is a concept in object-oriented programming where a class can inherit properties and behaviors from more than one parent class. This means that a subclass can have multiple immediate parent classes, allowing it to inherit features from each of them. - -**Polymorphism** In object oriented Programming Python, Polymorphism -simply means having many forms - -```python -class Bird: - - def intro(self): - print("There are many types of birds.") - - def flight(self): - print("Most of the birds can fly but some cannot.") - -class sparrow(Bird): - - def flight(self): - print("Sparrows can fly.") - -class ostrich(Bird): - - def flight(self): - print("Ostriches cannot fly.") - -obj_bird = Bird() -obj_spr = sparrow() -obj_ost = ostrich() - -obj_bird.intro() -obj_bird.flight() - -obj_spr.intro() -obj_spr.flight() - -obj_ost.intro() -obj_ost.flight() -``` -Poly stands for 'many' and morphism for 'forms'. In the above code, method flight() has many forms. - -**Python Encapsulation** - -In Python object oriented programming, Encapsulation is one of the -fundamental concepts in object-oriented programming (OOP). It describes -the idea of wrapping data and the methods that work on data within one -unit. This puts restrictions on accessing variables and methods directly -and can prevent the accidental modification of data. To prevent -accidental change, an object's variable can only be changed by an -object's method. Those types of variables are known as private -variables. - - -```python -class Car: - def __init__(self, make, model, year): - self._make = make # Encapsulated attribute with single underscore - self._model = model # Encapsulated attribute with single underscore - self._year = year # Encapsulated attribute with single underscore - self._odometer_reading = 0 # Encapsulated attribute with single underscore - - def get_make(self): - return self._make - - def get_model(self): - return self._model - - def get_year(self): - return self._year - - def get_odometer_reading(self): - return self._odometer_reading - - def update_odometer(self, mileage): - if mileage >= self._odometer_reading: - self._odometer_reading = mileage - else: - print("You can't roll back an odometer!") - - def increment_odometer(self, miles): - self._odometer_reading += miles - -# Creating an instance of the Car class -my_car = Car("Toyota", "Camry", 2021) - -# Accessing encapsulated attributes through methods -print("Make:", my_car.get_make()) -print("Model:", my_car.get_model()) -print("Year:", my_car.get_year()) - -# Modifying encapsulated attribute through method -my_car.update_odometer(100) -print("Odometer Reading:", my_car.get_odometer_reading()) - -# Incrementing odometer reading -my_car.increment_odometer(50) -print("Odometer Reading after increment:", my_car.get_odometer_reading()) -``` - - -**Data Abstraction** It hides unnecessary code details from the user. -Also, when we do not want to give out sensitive parts of our code -implementation and this is where data abstraction came. - -```python -from abc import ABC, abstractmethod - -# Abstract class defining the interface for a Shape -class Shape(ABC): - def __init__(self, name): - self.name = name - - @abstractmethod - def area(self): - pass - - @abstractmethod - def perimeter(self): - pass - -# Concrete class implementing the Shape interface for a Rectangle -class Rectangle(Shape): - def __init__(self, name, length, width): - super().__init__(name) - self.length = length - self.width = width - - def area(self): - return self.length * self.width - - def perimeter(self): - return 2 * (self.length + self.width) - -# Concrete class implementing the Shape interface for a Circle -class Circle(Shape): - def __init__(self, name, radius): - super().__init__(name) - self.radius = radius - - def area(self): - return 3.14 * self.radius * self.radius - - def perimeter(self): - return 2 * 3.14 * self.radius - -# Creating objects of the derived classes -rectangle = Rectangle("Rectangle", 5, 4) -circle = Circle("Circle", 3) - -# Accessing methods defined by the Shape interface -print(f"{rectangle.name}: Area = {rectangle.area()}, Perimeter = {rectangle.perimeter()}") -print(f"{circle.name}: Area = {circle.area()}, Perimeter = {circle.perimeter()}") -``` -To implement Data Abstraction , we have to import abc . ABC stands for Abstract Base Class . All those classes which want to implement data abstraction have to inherit from ABC. -@abstractmethod is a decorator provided by the abc module, which stands for "abstract method". It's used to define abstract methods within abstract base classes (ABCs). An abstract method is a method declared in a class, but it does not contain an implementation. Instead, it serves as a placeholder, and its concrete implementation must be provided by subclasses. -Abstract methods can be implemented by the derived classes. diff --git a/docs/python/Scipy.md b/docs/python/Scipy.md deleted file mode 100644 index 5f412e92e..000000000 --- a/docs/python/Scipy.md +++ /dev/null @@ -1,172 +0,0 @@ -# Scipy - -Scipy is a powerful Python library used for scientific and technical computing. It builds on NumPy and provides a large number of higher-level functions for mathematical operations, including optimization, integration, interpolation, eigenvalue problems, algebraic equations, and more. - -**1. Installation:** -```python -python -m pip install scipy -``` - -**2. Import and Usage:** - -```python -import numpy as np -from scipy import linalg, optimize, integrate, interpolate, stats -``` - -**3. Linear Algebra:** - -Scipy has many functions for linear algebra operations - -- Solving Linear Equations: -```python -import numpy as np -from scipy import linalg, optimize, integrate, interpolate, stats -# Solving the system of equations Ax = b -A = np.array([[3, 2], [1, 2]]) -b = np.array([2, 0]) - -x = linalg.solve(A, b) -print(x) # Solution to the system -``` - -- Eigenvalues and eigenvectors -```python -# Finding eigenvalues and eigenvectors -import numpy as np -from scipy import linalg, optimize, integrate, interpolate, stats - -A = np.array([[3, 2], [4, 1]]) - -eigenvalues, eigenvectors = linalg.eig(A) -print(eigenvalues) # Eigenvalues -print(eigenvectors) # Eigenvectors -``` - -**4. Optimization:** - -- Finding minima of a function: -```python -import numpy as np -from scipy import linalg, optimize, integrate, interpolate, stats - -# Minimizing a scalar function -def f(x): - return x**2 + 10*np.sin(x) - -result = optimize.minimize(f, x0=0) -print(result.x) # Minimum value of the function -``` - -- Root Finding -```python -import numpy as np -from scipy import linalg, optimize, integrate, interpolate, stats - -# Finding roots of a function -def f(x): - return x**2 - 4 - -root = optimize.root(f, x0=1) -print(root.x) # Root of the function -``` - -**5. Interpolation:** - -Interpolation can be useful when you want to estimate values between known data points. - -```python -import numpy as np -from scipy import linalg, optimize, integrate, interpolate, stats - -# Interpolating data -x = np.linspace(0, 10, 10) -y = np.sin(x) - -f = interpolate.interp1d(x, y) -x_new = np.linspace(0, 10, 50) -y_new = f(x_new) - -print(y_new) # Interpolated values -``` - -**6. Statistics:** - -Scipy's `stats` module provides a range of statistical functions. - -```python -import numpy as np -from scipy import linalg, optimize, integrate, interpolate, stats - - -# Calculating descriptive statistics -data = np.random.normal(loc=0, scale=1, size=1000) - -mean = stats.tmean(data) -std_dev = stats.tstd(data) - -print(mean) # Mean of the data -print(std_dev) # Standard deviation of the data -``` - - -**7. Signal Processing:** - -Scipy's `signal` module is a powerful tool for signal processing tasks in Python. It provides functions for filtering, spectral analysis, interpolation, and other signal-related operations. - -- Filtering: - -```python -from scipy import signal -import numpy as np -import matplotlib.pyplot as plt - -# Generate a noisy signal -np.random.seed(0) -t = np.linspace(0, 1, 1000) -x = np.sin(2 * np.pi * 10 * t) + np.random.normal(0, 1, t.shape) - -# Design a low-pass FIR filter -b = signal.firwin(30, 0.05) -x_filtered = signal.lfilter(b, 1, x) - -# Plotting -plt.figure(figsize=(10, 4)) -plt.plot(t, x, label='Noisy signal') -plt.plot(t, x_filtered, label='Filtered signal') -plt.xlabel('Time') -plt.ylabel('Amplitude') -plt.legend() -plt.show() -``` - -Output: - -![image](https://github.com/AmrutaJayanti/codeharborhub/assets/142327526/63a9d70a-af17-414b-beb4-563832da68d5) - - -- Spectral Analysis: - -```python -from scipy import signal -import numpy as np -import matplotlib.pyplot as plt - - -# Compute and plot a spectrogram -f, t, Sxx = signal.spectrogram(x, fs=1000) -plt.figure(figsize=(10, 4)) -plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud') -plt.ylabel('Frequency [Hz]') -plt.xlabel('Time [sec]') -plt.colorbar(label='Power [dB]') -plt.show() -``` - -Output: - -![image](https://github.com/AmrutaJayanti/codeharborhub/assets/142327526/30e09ff7-3ad0-424e-993d-96825ad44fb1) - - - - diff --git a/docs/python/Strings.md b/docs/python/Strings.md deleted file mode 100644 index af08edc81..000000000 --- a/docs/python/Strings.md +++ /dev/null @@ -1,426 +0,0 @@ ---- -id: Strings -title: Strings in Python -sidebar_label: String in Python -sidebar_position: 5 -tags: [python] -description: In this tutorial, we will explore the basics of strings in Python, including how to create, manipulate, and format strings. ---- - -# Strings in Python - -Strings in Python are surrounded by either single quotation marks or double quotation marks. `'hello'` is the same as `"hello"`. - -You can display a string literal with the `print()` function: - -```python -print("Hello") -print('Hello') -``` - -## Quotes Inside Quotes - -You can use quotes inside a string, as long as they don't match the quotes surrounding the string: - -```python -print("It's alright") -print("He is called 'Johnny'") -print('He is called "Johnny"') -``` - -## Assign String to a Variable - -Assigning a string to a variable is done with the variable name followed by an equal sign and the string: - -```python -a = "Hello" -print(a) -``` - -## Multiline Strings - -You can assign a multiline string to a variable by using three quotes: - -You can use three double quotes: - -```python -a = """Lorem ipsum dolor sit amet, -consectetur adipiscing elit, -sed do eiusmod tempor incididunt -ut labore et dolore magna aliqua.""" -print(a) -``` - -Or three single quotes: - -```python -a = '''Lorem ipsum dolor sit amet, -consectetur adipiscing elit, -sed do eiusmod tempor incididunt -ut labore et dolore magna aliqua.''' -print(a) -``` - -**Note**: In the result, the line breaks are inserted at the same position as in the code. - -## Strings are Arrays - -Like many other popular programming languages, strings in Python are arrays of bytes representing Unicode characters. However, Python does not have a character data type; a single character is simply a string with a length of 1. - -Square brackets can be used to access elements of the string: - -```python -a = "Hello, World!" -print(a[1]) -``` - -## Looping Through a String - -Since strings are arrays, we can loop through the characters in a string with a `for` loop: - -```python -for x in "banana": - print(x) -``` - -## String Length - -To get the length of a string, use the `len()` function: - -```python -a = "Hello, World!" -print(len(a)) -``` - -## Check String - -To check if a certain phrase or character is present in a string, we can use the keyword `in`. - -### Example - -Check if "free" is present in the following text: - -```python -txt = "The best things in life are free!" -print("free" in txt) -``` - -Use it in an `if` statement: - -```python -txt = "The best things in life are free!" -if "free" in txt: - print("Yes, 'free' is present.") -``` - -## Check if NOT - -To check if a certain phrase or character is NOT present in a string, we can use the keyword `not in`. - -### Example - -Check if "expensive" is NOT present in the following text: - -```python -txt = "The best things in life are free!" -print("expensive" not in txt) -``` - -Use it in an `if` statement: - -```python -txt = "The best things in life are free!" -if "expensive" not in txt: - print("No, 'expensive' is NOT present.") -``` - -## Slicing - -You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string. - -### Example - -Get the characters from position 2 to position 5 (not included): - -```python -b = "Hello, World!" -print(b[2:5]) -``` - -**Note**: The first character has index 0. - -### Slice From the Start - -By leaving out the start index, the range will start at the first character: - -```python -b = "Hello, World!" -print(b[:5]) -``` - -### Slice To the End - -By leaving out the end index, the range will go to the end: - -```python -b = "Hello, World!" -print(b[2:]) -``` - -### Negative Indexing - -Use negative indexes to start the slice from the end of the string: - -### Example - -Get the characters: - -From: `"o"` in `"World!"` (position -5) - -To, but not included: `"d"` in `"World!"` (position -2): - -```python -b = "Hello, World!" -print(b[-5:-2]) -``` - -## Modify Strings - -Python has a set of built-in methods that you can use on strings. - -### Upper Case - -The `upper()` method returns the string in upper case: - -```python -a = "Hello, World!" -print(a.upper()) -``` - -### Lower Case - -The `lower()` method returns the string in lower case: - -```python -a = "Hello, World!" -print(a.lower()) -``` - -### Remove Whitespace - -Whitespace is the space before and/or after the actual text, and very often you want to remove this space. - -The `strip()` method removes any whitespace from the beginning or the end: - -```python -a = " Hello, World! " -print(a.strip()) # returns "Hello, World!" -``` - -### Replace String - -The `replace()` method replaces a string with another string: - -```python -a = "Hello, World!" -print(a.replace("H", "J")) -``` - -### Split String - -The `split()` method returns a list where the text between the specified separator becomes the list items. - -The `split()` method splits the string into substrings if it finds instances of the separator: - -```python -a = "Hello, World!" -print(a.split(",")) # returns ['Hello', ' World!'] -``` - -## String Concatenation - -To concatenate, or combine, two strings, you can use the `+` operator. - -### Example - -Merge variable `a` with variable `b` into variable `c`: - -```python -a = "Hello" -b = "World" -c = a + b -print(c) -``` - -To add a space between them, add a `" "`: - -```python -a = "Hello" -b = "World" -c = a + " " + b -print(c) -``` - -## String Format - -As we learned in the Python Variables chapter, we cannot combine strings and numbers like this: - -### Example - -```python -age = 36 -txt = "My name is John, I am " + age -print(txt) -``` - -But we can combine strings and numbers by using f-strings or the `format()` method! - -### F-Strings - -F-String was introduced in Python 3.6 and is now the preferred way of formatting strings. - -To specify a string as an f-string, simply put an `f` in front of the string literal, and add curly brackets `{}` as placeholders for variables and other operations. - -### Example - -Create an f-string: - -```python -age = 36 -txt = f"My name is John, I am {age}" -print(txt) -``` - -### Placeholders and Modifiers - -A placeholder can contain variables, operations, functions, and modifiers to format the value. - -### Example - -Add a placeholder for the price variable: - -```python -price = 59 -txt = f"The price is {price} dollars" -print(txt) -``` - -A placeholder can include a modifier to format the value. - -A modifier is included by adding a colon `:` followed by a legal formatting type, like `.2f` which means fixed-point number with 2 decimals: - -### Example - -Display the price with 2 decimals: - -```python -price = 59 -txt = f"The price is {price:.2f} dollars" -print(txt) -``` - -A placeholder can contain Python code, like math operations: - -### Example - -Perform a math operation in the placeholder, and return the result: - -```python -txt = f"The price is {20 * 59} dollars" -print(txt) -``` - -## Escape Characters - -To insert characters that are illegal in a string, use an escape character. - -An escape character is a backslash `\` followed by the character you want to insert. - -An example of an illegal character is a double quote inside a string that is surrounded by double quotes: - -### Example - -You will get an error if you use double quotes inside a string that is surrounded by double quotes: - -```python -txt = "We are the so-called "Vikings" from the north." -``` - -To fix this problem, use the escape character `\"`: - -### Example - -The escape character allows you to use double quotes when you normally would not be allowed: - -```python -txt = "We are the so-called \"Vikings\" from the north." -``` - -### Other Escape Characters - -Other escape characters used in Python: - -| Code | Result | -|---------|------------------| -| `\'` | Single Quote | -| `\\` | Backslash | -| `\n` | New Line | -| `\r` | Carriage Return | -| `\t` | Tab | -| `\b` | Backspace | -| `\f` | Form Feed | -| `\ooo` | Octal value | -| `\xhh` | Hex value | - -## String Methods - -Python has a set of built-in methods that you can use on strings. All string methods return new values. They do not change the original string. - -| Method | Description | -|-----------------|--------------------------------------------------------| -| `capitalize()` | Converts the first character to upper case | -| `casefold()` | Converts string into lower case | -| `center()` | Returns a centeredstring | -| `count()` | Returns the number of times a specified value occurs in a string | -| `encode()` | Returns an encoded version of the string | -| `endswith()` | Returns true if the string ends with the specified value | -| `expandtabs()` | Sets the tab size of the string | -| `find()` | Searches the string for a specified value and returns the position of where it was found | -| `format()` | Formats specified values in a string | -| `format_map()` | Formats specified values in a string | -| `index()` | Searches the string for a specified value and returns the position of where it was found | -| `isalnum()` | Returns True if all characters in the string are alphanumeric | -| `isalpha()` | Returns True if all characters in the string are in the alphabet | -| `isascii()` | Returns True if all characters in the string are ASCII characters | -| `isdecimal()` | Returns True if all characters in the string are decimals | -| `isdigit()` | Returns True if all characters in the string are digits | -| `isidentifier()`| Returns True if the string is an identifier | -| `islower()` | Returns True if all characters in the string are lower case | -| `isnumeric()` | Returns True if all characters in the string are numeric | -| `isprintable()` | Returns True if all characters in the string are printable | -| `isspace()` | Returns True if the string contains only whitespace characters | -| `istitle()` | Returns True if the string follows the rules of a title | -| `isupper()` | Returns True if all characters in the string are upper case | -| `join()` | Joins the elements of an iterable to the end of the string | -| `ljust()` | Returns a left justified version of the string | -| `lower()` | Converts a string into lower case | -| `lstrip()` | Returns a left trim version of the string | -| `maketrans()` | Returns a translation table to be used in translations | -| `partition()` | Returns a tuple where the string is parted into three parts | -| `replace()` | Returns a string where a specified value is replaced with another specified value | -| `rfind()` | Searches the string for a specified value and returns the last position of where it was found | -| `rindex()` | Searches the string for a specified value and returns the last position of where it was found | -| `rjust()` | Returns a right justified version of the string | -| `rpartition()` | Returns a tuple where the string is parted into three parts | -| `rsplit()` | Splits the string at the specified separator, and returns a list | -| `rstrip()` | Returns a right trim version of the string | -| `split()` | Splits the string at the specified separator, and returns a list | -| `splitlines()` | Splits the string at line breaks and returns a list | -| `startswith()` | Returns true if the string starts with the specified value | -| `strip()` | Returns a trimmed version of the string | -| `swapcase()` | Swaps cases, lower case becomes upper case and vice versa | -| `title()` | Converts the first character of each word to upper case | -| `translate()` | Returns a translated string | -| `upper()` | Converts a string into upper case | -| `zfill()` | Fills the string with a specified number of 0 values at the beginning | - diff --git a/docs/python/_category_.json b/docs/python/_category_.json deleted file mode 100644 index 0c27a66a8..000000000 --- a/docs/python/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Python", - "position": 21, - "link": { - "type": "generated-index", - "description": "Python is a high-level, interpreted programming language with easy syntax and dynamic typing. It is known for its simplicity and readability, which makes it a great language for beginners. Python supports multiple programming paradigms and has a large standard library. It's used in various domains like web development, data analysis, machine learning, AI, and more." - } - } \ No newline at end of file diff --git a/docs/python/conditional.md b/docs/python/conditional.md deleted file mode 100644 index f4fd13529..000000000 --- a/docs/python/conditional.md +++ /dev/null @@ -1,212 +0,0 @@ ---- -id: Python_Conditional_Statements -title: Python Conditional Statements -sidebar_label: Conditional Statements -tags: [python, conditional-statements] ---- - -# Python Conditional Statements - -Python supports the usual logical conditions from mathematics: - -- Equals: `a == b` -- Not Equals: `a != b` -- Less than: `a < b` -- Less than or equal to: `a <= b` -- Greater than: `a > b` -- Greater than or equal to: `a >= b` - -These conditions can be used in several ways, most commonly in "if statements" and loops. - -## If Statement - -An "if statement" is written by using the `if` keyword. - -### Example - -```python -a = 33 -b = 200 -if b > a: - print("b is greater than a") -``` - -## Indentation - -Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. - -### Example - -If statement, without indentation (will raise an error): - -```python -a = 33 -b = 200 -if b > a: -print("b is greater than a") # you will get an error -``` - -## Elif - -The `elif` keyword is Python's way of saying "if the previous conditions were not true, then try this condition". - -### Example - -```python -a = 33 -b = 33 -if b > a: - print("b is greater than a") -elif a == b: - print("a and b are equal") -``` - -## Else - -The `else` keyword catches anything which isn't caught by the preceding conditions. -![if else image](https://images.wondershare.com/edrawmax/article2023/flowchart-if-else/if-else-statements-flowcharts-insight.jpg) -### Example - -```python -a = 200 -b = 33 -if b > a: - print("b is greater than a") -elif a == b: - print("a and b are equal") -else: - print("a is greater than b") -``` - -You can also have an `else` without the `elif`: - -### Example - -```python -a = 200 -b = 33 -if b > a: - print("b is greater than a") -else: - print("b is not greater than a") -``` - -## Short Hand If - -If you have only one statement to execute, you can put it on the same line as the `if` statement. - -### Example - -One line if statement: - -```python -if a > b: print("a is greater than b") -``` - -## Short Hand If ... Else - -If you have only one statement to execute, one for if, and one for else, you can put it all on the same line. - -### Example - -One line if else statement: - -```python -a = 2 -b = 330 -print("A") if a > b else print("B") -``` - -This technique is known as Ternary Operators, or Conditional Expressions. - -You can also have multiple `else` statements on the same line: - -### Example - -One line if else statement, with 3 conditions: - -```python -a = 330 -b = 330 -print("A") if a > b else print("=") if a == b else print("B") -``` - -## And - -The `and` keyword is a logical operator, and is used to combine conditional statements. - -### Example - -Test if `a` is greater than `b`, AND if `c` is greater than `a`: - -```python -a = 200 -b = 33 -c = 500 -if a > b and c > a: - print("Both conditions are True") -``` - -## Or - -The `or` keyword is a logical operator, and is used to combine conditional statements. - -### Example - -Test if `a` is greater than `b`, OR if `a` is greater than `c`: - -```python -a = 200 -b = 33 -c = 500 -if a > b or a > c: - print("At least one of the conditions is True") -``` - -## Not - -The `not` keyword is a logical operator, and is used to reverse the result of the conditional statement. - -### Example - -Test if `a` is NOT greater than `b`: - -```python -a = 33 -b = 200 -if not a > b: - print("a is NOT greater than b") -``` - -## Nested If - -You can have if statements inside if statements; this is called nested if statements. - -### Example - -```python -x = 41 - -if x > 10: - print("Above ten,") - if x > 20: - print("and also above 20!") - else: - print("but not above 20.") -``` - -## The pass Statement - -If statements cannot be empty, but if you, for some reason, have an if statement with no content, put in the `pass` statement to avoid getting an error. - -### Example - -```python -a = 33 -b = 200 - -if b > a: - pass -``` - -This documentation covers the basics of Python conditional statements, including if, elif, else, nested if statements, and logical operators. Proper indentation and examples are provided for clarity. \ No newline at end of file diff --git a/docs/python/feature-engineering.md b/docs/python/feature-engineering.md deleted file mode 100644 index 078a6c8b4..000000000 --- a/docs/python/feature-engineering.md +++ /dev/null @@ -1,864 +0,0 @@ - -**Feature:** - -In the context of machine learning, a feature (also known as a variable -or attribute) is an individual measurable property or characteristic of -a data point that is used as input for a machine learning algorithm. -Features can be numerical, categorical, or text-based, and they -represent different aspects of the data that are relevant to the problem -at hand. - -For example, in a dataset of housing prices, features could include the -number of bedrooms, the square footage, the location, and the age of the -property. In a dataset of customer demographics, features could include -age, gender, income level, and occupation. - -**What is Feature Engineering?** - -Feature engineering is the process of transforming raw data into -features that are suitable for machine learning models. In other words, -it is the process of selecting, extracting, and transforming the most -relevant features from the available data to build more accurate and -efficient machine learning models. - -**Why need it?** - -*Improve User Experience:* The primary reason we engineer features is to -enhance the user experience of a product or service. By adding new -features, we can make the product more intuitive, efficient, and -user-friendly, which can increase user satisfaction and engagement. - -*Competitive Advantage:* Another reason we engineer features is to gain -a competitive advantage in the marketplace. By offering unique and -innovative features, we can differentiate our product from competitors -and attract more customers. - -*Meet Customer Needs:* We engineer features to meet the evolving needs -of customers. By analyzing user feedback, market trends, and customer -behavior, we can identify areas where new features could enhance the -product's value and meet customer needs. - -*Increase Revenue:* Features can also be engineered to generate more -revenue. For example, a new feature that streamlines the checkout -process can increase sales, or a feature that provides additional -functionality could lead to more upsells or cross-sells. - -*Future-Proofing:* Engineering features can also be done to future-proof -a product or service. By anticipating future trends and potential -customer needs, we can develop features that ensure the product remains -relevant and useful in the long term. - -![FE](https://tse3.mm.bing.net/th?id=OIP.sCoM-hxdiEZW73coQYeQawHaDA&pid=Api&P=0&h=180) - -**Processes involved:-** - -- Feature Transformation - -- Feature Construction - -- Feature Extraction - -- Feature Selection - -**FEATURE TRANSFORMATION:-** - -Feature Transformation is the process of transforming the features into -a more suitable representation for the machine learning model. This is -done to ensure that the model can effectively learn from the data. - -- Missing Value Imputation -- Handling Categorical Values -- Outlier Detection -- Feature Scaling - -1.) Missing Value Imputation - -Missing value imputation is a critical step in data preprocessing where -missing data points are filled in with estimated values. - -- Simple Imputation - -- K-Nearest Neighbours (KNN) Imputation - -- Multivariate Imputation by Chained Equations (MICE) - -**SIMPLE IMPUTATION** -: -``` python -#Simple Imputation -#Lets first create Some sample dataset -import numpy as np -import pandas as pd - -# Sample DataFrame -data = { - 'A': [1, 2, np.nan, 4, 5], - 'B': [np.nan, 2, 3, 4, 5], - 'C': ['cat', 'dog', np.nan, 'mouse', 'rabbit'] -} -df = pd.DataFrame(data) -print("Original DataFrame:") -print(df) -``` - -Output: - - Original DataFrame: - A B C - 0 1.0 NaN cat - 1 2.0 2.0 dog - 2 NaN 3.0 NaN - 3 4.0 4.0 mouse - 4 5.0 5.0 rabbit - -Mean Imputation - -``` python -from sklearn.impute import SimpleImputer - -# Mean Imputation for numerical columns -mean_imputer = SimpleImputer(strategy='mean') -df['A'] = mean_imputer.fit_transform(df[['A']]) - -print("\nDataFrame after Mean Imputation:") -print(df) -``` -Output: - - DataFrame after Mean Imputation: - A B C - 0 1.0 NaN cat - 1 2.0 2.0 dog - 2 3.0 3.0 NaN - 3 4.0 4.0 mouse - 4 5.0 5.0 rabbit - -The above code performs Mean imputation. - -Replacing missing values with the mean of the column - -`SimpleImputer` is a class in the `sklearn.impute` module of the -Scikit-learn library, used for handling missing data by providing basic -strategies for imputing missing values. It replaces missing values with -specified constant values or statistical values (like mean, median, or -mode) of the corresponding column. - -Above code selects the column A and then replaces `NaN` with mean of the -column - -``` python -# Median Imputation for numerical columns -median_imputer = SimpleImputer(strategy='median') -df['B'] = median_imputer.fit_transform(df[['B']]) - -print("\nDataFrame after Median Imputation:") -print(df) -``` - -Output: - - DataFrame after Median Imputation: - A B C - 0 1.0 3.5 cat - 1 2.0 2.0 dog - 2 3.0 3.0 NaN - 3 4.0 4.0 mouse - 4 5.0 5.0 rabbit - -Above code is for median imputation. - -Replacing missing values with the median of the column. Useful for -skewed distributions. - -Above code selects the column B and then replaces `Nan` with the median -of the column. - -**KNN IMPUTATION** - -``` python -import numpy as np -import pandas as pd -from sklearn.impute import KNNImputer -# Sample DataFrame -data = { - 'A': [1, 2, np.nan, 4, 5], - 'B': [np.nan, 2, 3, 4, 5], - 'C': [7, 8, 9, np.nan, 11] -} -df = pd.DataFrame(data) -print("Original DataFrame:") -print(df) -# Initialize the KNNImputer -knn_imputer = KNNImputer(n_neighbors=3) - -# Fit the imputer and transform the data -df_imputed = pd.DataFrame(knn_imputer.fit_transform(df), columns=df.columns) - -print("\nDataFrame after KNN Imputation:") -print(df_imputed) -``` - -Output: - - Original DataFrame: - A B C - 0 1.0 NaN 7.0 - 1 2.0 2.0 8.0 - 2 NaN 3.0 9.0 - 3 4.0 4.0 NaN - 4 5.0 5.0 11.0 - - - DataFrame after KNN Imputation: - A B C - 0 1.000000 3.0 7.000000 - 1 2.000000 2.0 8.000000 - 2 2.333333 3.0 9.000000 - 3 4.000000 4.0 9.333333 - 4 5.000000 5.0 11.000000 - -KNN (K-Nearest Neighbors) imputation is a method that replaces missing -values by considering the values of the nearest neighbors. The KNN -imputer finds the k-nearest neighbors of an instance with missing values -and then uses their values to fill in the gaps. This method can handle -both numerical and categorical data, and it tends to be more robust than -simpler imputation methods like mean or median imputation. - -Scikit-learn provides a `KNNImputer` class in the `sklearn.impute` -module, which makes it straightforward to perform KNN imputation. - -**MULTIVARIATE IMPUTATION BY CHAINED EQUATIONS** - -``` python -import numpy as np -import pandas as pd -from sklearn.experimental import enable_iterative_imputer -from sklearn.impute import IterativeImputer - -# Sample DataFrame -data = { - 'A': [1, 2, np.nan, 4, 5], - 'B': [np.nan, 2, 3, 4, 5], - 'C': [7, 8, 9, np.nan, 11] -} -df = pd.DataFrame(data) -print("Original DataFrame:") -print(df) - -# Initialize the IterativeImputer -mice_imputer = IterativeImputer(max_iter=10, random_state=0) - -# Fit the imputer and transform the data -df_imputed = pd.DataFrame(mice_imputer.fit_transform(df), columns=df.columns) - -print("\nDataFrame after MICE Imputation:") -print(df_imputed) -``` - -Output: - - Original DataFrame: - A B C - 0 1.0 NaN 7.0 - 1 2.0 2.0 8.0 - 2 NaN 3.0 9.0 - 3 4.0 4.0 NaN - 4 5.0 5.0 11.0 - - DataFrame after MICE Imputation: - A B C - 0 1.00000 0.999988 7.000000 - 1 2.00000 2.000000 8.000000 - 2 3.00005 3.000000 9.000000 - 3 4.00000 4.000000 9.999993 - 4 5.00000 5.000000 11.000000 - -Multivariate Imputation by Chained Equations (MICE), also known as Fully -Conditional Specification (FCS), is a method for handling missing data -by iteratively imputing each missing value using a regression model. It -allows for complex relationships between variables and can provide more -accurate imputations than simpler methods. - -In this example, the `IterativeImputer` iteratively imputes the missing -values in columns \'A\', \'B\', and \'C\' using regression models. This -imputation method takes into account the relationships between all the -columns, providing a more accurate imputation than simpler methods. - -2.)Handling categorical values Handling categorical values is a critical -step in feature transformation for machine learning. Categorical data -can be transformed into numerical values in various ways to make them -suitable for modeling. - -Common techniques used to handle categorical values:- - -- One Hot Encoding - -- Label Encoding - -- Ordinal Encoding - -**One-Hot Encoding** - -One-hot encoding transforms categorical variables into a set of binary -columns. Each category is represented as a binary column (0 or 1). - -``` python -import pandas as pd -from sklearn.preprocessing import OneHotEncoder - -# Sample DataFrame -data = {'Color': ['Red', 'Blue', 'Green', 'Blue', 'Red']} -df = pd.DataFrame(data) - -# Initialize the OneHotEncoder -onehot_encoder = OneHotEncoder(sparse_output=False) - -# Fit and transform the data -onehot_encoded = onehot_encoder.fit_transform(df[['Color']]) - -# Create a DataFrame with the encoded features -onehot_encoded_df = pd.DataFrame(onehot_encoded, columns=onehot_encoder.get_feature_names_out(['Color'])) - -print(onehot_encoded_df) -``` - -Output: - - Color_Blue Color_Green Color_Red - 0 0.0 0.0 1.0 - 1 1.0 0.0 0.0 - 2 0.0 1.0 0.0 - 3 1.0 0.0 0.0 - 4 0.0 0.0 1.0 - -Above code performs one hot encoding. `get_features_names_out` extracts -the features present in the dataset. - -**Label Encoding** - -Label encoding converts each category into a numerical value. This can -be useful for ordinal data but may not be suitable for nominal data -since it introduces an ordinal relationship between categories. - -``` python -from sklearn.preprocessing import LabelEncoder - -# Sample DataFrame -data = {'Color': ['Red', 'Blue', 'Green', 'Blue', 'Red']} -df = pd.DataFrame(data) - -# Initialize the LabelEncoder -label_encoder = LabelEncoder() - -# Fit and transform the data -df['Color_Encoded'] = label_encoder.fit_transform(df['Color']) - -print(df) -``` - -Output: - - Color Color_Encoded - 0 Red 2 - 1 Blue 0 - 2 Green 1 - 3 Blue 0 - 4 Red 2 - -`LabelEncoder` assigns each color in the above code with a numerical -value. - -Blue - 0 - -Green - 1 - -Red - 2 - -**Ordinal Encoding** - -Ordinal encoding is useful for ordinal categorical data where there is -an inherent order. It assigns integers to categories while preserving -the order. - -``` python -from sklearn.preprocessing import OrdinalEncoder - -# Sample DataFrame -data = {'Size': ['Small', 'Medium', 'Large', 'Medium', 'Small']} -df = pd.DataFrame(data) - -# Initialize the OrdinalEncoder -ordinal_encoder = OrdinalEncoder(categories=[['Small', 'Medium', 'Large']]) - -# Fit and transform the data -df['Size_Encoded'] = ordinal_encoder.fit_transform(df[['Size']]) - -print(df) -``` - -Output: - - Size Size_Encoded - 0 Small 0.0 - 1 Medium 1.0 - 2 Large 2.0 - 3 Medium 1.0 - 4 Small 0.0 - -Above code encodes the ordinal data \[Small,Medium,Large\] based on -their ranking by assigning a numerical value to it . - -3.)Outlier Detection:Outlier detection is an important step in data -preprocessing as outliers can significantly affect the performance of -machine learning models. Outliers are data points that differ -significantly from other observations in the dataset. Detecting and -handling outliers can improve model accuracy and reliability. - -Here are some common techniques for detecting outliers: - -- Z-score -- Interquartile Range (IQR) - -**Z-Score (Standard Score)** - -Z-score is a measure of how many standard deviations a data point is -from the mean. It assumes that the data follows a Gaussian (normal) -distribution. - -![Zscore](https://tse4.mm.bing.net/th?id=OIP.WF_pHaZPSWI5RNvMOcH8zQAAAA&pid=Api&P=0&h=180) - -``` python -import numpy as np -import pandas as pd - -# Sample DataFrame -data = {'Value': [10, 12, 12, 13, 12, 14, 100, 12, 15, 10, 12]} -df = pd.DataFrame(data) - -# Calculate Z-scores -df['Z-Score'] = (df['Value'] - df['Value'].mean()) / df['Value'].std() - -# Identify outliers -threshold = 3 -df['Outlier'] = df['Z-Score'].abs() > threshold - -print(df) -``` - - -Output: - - Value Z-Score Outlier - 0 10 -0.384024 False - 1 12 -0.308591 False - 2 12 -0.308591 False - 3 13 -0.270874 False - 4 12 -0.308591 False - 5 14 -0.233158 False - 6 100 3.010478 True - 7 12 -0.308591 False - 8 15 -0.195441 False - 9 10 -0.384024 False - 10 12 -0.308591 False - - -Particular data item z-score is calculated and if value is greater than -given threshold value then it returns `True` else `False` - - -**Interquartile Range (IQR)** - -The IQR method is based on the quartiles of the data. Outliers are -defined as points outside the range \[Q1 - 1.5 \* IQR, Q3 + 1.5 \* -IQR\], where Q1 is the first quartile and Q3 is the third quartile. - -``` python -# Calculate IQR -Q1 = df['Value'].quantile(0.25) -Q3 = df['Value'].quantile(0.75) -IQR = Q3 - Q1 - -# Define outlier thresholds -lower_bound = Q1 - 1.5 * IQR -upper_bound = Q3 + 1.5 * IQR - -# Identify outliers -df['Outlier'] = (df['Value'] < lower_bound) | (df['Value'] > upper_bound) - -print(df) -``` - -Output: - - Value Z-Score Outlier - 0 10 -0.384024 False - 1 12 -0.308591 False - 2 12 -0.308591 False - 3 13 -0.270874 False - 4 12 -0.308591 False - 5 14 -0.233158 False - 6 100 3.010478 True - 7 12 -0.308591 False - 8 15 -0.195441 False - 9 10 -0.384024 False - 10 12 -0.308591 False - - -lower_bound and upper_bound mentions the range. Below lower_bound or -above upper_bound then data point is said to be an outlier - - - - -4.)Feature Scaling:Feature scaling is a crucial step in data -preprocessing for machine learning. It ensures that the numerical -features are on a similar scale, which can improve the performance of -many machine learning algorithms. - -Here are some common methods of feature scaling: - -- Standardization -- Normalisation - - -**Standardization** - -It is also called z-score Normalisation. - -`Z = (X - μ) / σ` - - -``` python -from sklearn.preprocessing import StandardScaler - -# Initialize the StandardScaler -scaler = StandardScaler() - -# Fit and transform the data -df['Value_Standardized'] = scaler.fit_transform(df[['Value']]) - -print(df) -``` - -Output: - - Value Z-Score Outlier Value_Standardized - 0 10 -0.384024 False -0.402768 - 1 12 -0.308591 False -0.323653 - 2 12 -0.308591 False -0.323653 - 3 13 -0.270874 False -0.284095 - 4 12 -0.308591 False -0.323653 - 5 14 -0.233158 False -0.244538 - 6 100 3.010478 True 3.157416 - 7 12 -0.308591 False -0.323653 - 8 15 -0.195441 False -0.204980 - 9 10 -0.384024 False -0.402768 - 10 12 -0.308591 False -0.323653 - -Above code uses `StandardScaler` to standardize the values - -**Normalisation** - -- MinMax Scaling - -- Robust Scaling - -- MaxAbs Scaling - - -**MinMax Scaling** - -Min-max scaling transforms the features to a fixed range, usually \[0, -1\]. - -![MinMax](https://tse4.mm.bing.net/th?id=OIP.vBO3wyehnnOLY67eMrXt7wHaCS&pid=Api&P=0&h=180) - - -``` python -import pandas as pd -from sklearn.preprocessing import MinMaxScaler - -# Sample DataFrame -data = {'Value': [10, 20, 30, 40, 50]} -df = pd.DataFrame(data) - -# Initialize the MinMaxScaler -scaler = MinMaxScaler() - -# Fit and transform the data -df['Value_Scaled'] = scaler.fit_transform(df[['Value']]) - -print(df) -``` - -Output: - - Value Value_Scaled - 0 10 0.00 - 1 20 0.25 - 2 30 0.50 - 3 40 0.75 - 4 50 1.00 - -`MinMaxScaler` is used to perform MinMaxScaling. - - -**Robust Scaling** - -Robust scaling uses the median and the interquartile range (IQR). It is -useful for data with outliers. - -![Robust](https://tse1.mm.bing.net/th?id=OIP.g0PtmCXLTAQJmzKyAUJQPAAAAA&pid=Api&P=0&h=180) - -``` python -from sklearn.preprocessing import RobustScaler - -# Initialize the RobustScaler -scaler = RobustScaler() - -# Fit and transform the data -df['Value_Robust'] = scaler.fit_transform(df[['Value']]) - -print(df) -``` -Output: - - Value Value_Scaled Value_Robust - 0 10 0.00 -1.0 - 1 20 0.25 -0.5 - 2 30 0.50 0.0 - 3 40 0.75 0.5 - 4 50 1.00 1.0 - -`RobustScaler' is used for performing Robust Scaling - -**MaxAbs Scaling** - -MaxAbs scaling scales each feature by its maximum absolute value. The -result is a dataset where each feature has a range of \[-1, 1\]. - -![MaxAbs](https://tse4.mm.bing.net/th?id=OIP.dQzNvcQua99b3Pwyk0VnoAAAAA&pid=Api&P=0&h=180) - -``` python -from sklearn.preprocessing import MaxAbsScaler - -# Initialize the MaxAbsScaler -scaler = MaxAbsScaler() - -# Fit and transform the data -df['Value_MaxAbs'] = scaler.fit_transform(df[['Value']]) - -print(df) -``` -Output: - - Value Value_Scaled Value_Robust Value_MaxAbs - 0 10 0.00 -1.0 0.2 - 1 20 0.25 -0.5 0.4 - 2 30 0.50 0.0 0.6 - 3 40 0.75 0.5 0.8 - 4 50 1.00 1.0 1.0 - -`MaxAbsScaler` performs the MaxAbs Scaling - -**FEATURE CONSTRUCTION** - -Feature construction, involves creating new features from the existing -ones to improve the performance of machine learning models. - -- Polynomial Features - -- Interaction Features - -- Logarithmic and Exponential Transformations - -**Polynomial Features** - -Creating polynomial features involves generating new features by taking -combinations of existing features to a certain power. - -``` python -from sklearn.preprocessing import PolynomialFeatures - -# Sample data -X = [[2, 3], [3, 4], [4, 5]] - -# Create polynomial features -poly = PolynomialFeatures(degree=2) -X_poly = poly.fit_transform(X) - -print(X_poly) -``` - -Output: - - [[ 1. 2. 3. 4. 6. 9.] - [ 1. 3. 4. 9. 12. 16.] - [ 1. 4. 5. 16. 20. 25.]] - -If you have a feature X , polynomial features could be X\^2, X\^3 - -**Interaction Features** - -Interaction features are created by multiplying two or more existing -features to capture interactions between variables. - -``` python -import pandas as pd - -# Sample data -X = pd.DataFrame({'X1': [1, 2, 3], 'X2': [4, 5, 6]}) - -# Create interaction features -X['X1_X2'] = X['X1'] * X['X2'] - -print(X) -``` -Output: - - X1 X2 X1_X2 - 0 1 4 4 - 1 2 5 10 - 2 3 6 18 - -For features 𝑋1 and 𝑋2, interaction features could be 𝑋 1 × 𝑋 2 - -**Logarithmic and Exponential Transformations** - -Applying logarithmic or exponential transformations can stabilize -variance and make the data more normally distributed. - -``` python -import numpy as np - -# Sample data -X = np.array([1, 2, 3, 4, 5]) - -# Apply logarithmic transformation -X_log = np.log(X) - -print(X_log) -``` -Output: - - [0. 0.69314718 1.09861229 1.38629436 1.60943791] - -For a feature 𝑋 , a logarithmic transformation could be log ( 𝑋 ) - -**FEATURE EXTRACTION** - -Feature extraction is a process of transforming raw data into a set of -features that can be used for machine learning models. The goal is to -reduce the dimensionality of the data while preserving its relevant -information. - -- Principal Component Analysis -- Linear Discriminant Analysis - -**Principal Component Analysis (PCA)** - -Principal Component Analysis (PCA) is a technique that transforms the -data into a new coordinate system such that the greatest variances by -any projection of the data come to lie on the first coordinates (called -principal components). - -``` python -from sklearn.decomposition import PCA -import numpy as np - -# Sample data -X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) - -# Apply PCA -pca = PCA(n_components=1) -X_pca = pca.fit_transform(X) - -print(X_pca) -``` - -Output: - - [[ 4.24264069] - [ 1.41421356] - [-1.41421356] - [-4.24264069]] - -`PCA` is used for Principal component analysis - -**Linear Discriminant Analysis (LDA)** - -Linear Discriminant Analysis (LDA) is a technique used to find a linear -combination of features that separates two or more classes of objects or -events. - -``` python -from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA -import numpy as np - -# Sample data -X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) -y = np.array([0, 1, 0, 1]) - -# Apply LDA -lda = LDA(n_components=1) -X_lda = lda.fit_transform(X, y) - -print(X_lda) -``` -Output: - - [[-1.06066017] - [-0.35355339] - [ 0.35355339] - [ 1.06066017]] - -`LinearDiscriminantAnalysis` is used - -**Feature Selection** - -Feature selection is the process of selecting a subset of relevant -features (variables, predictors) for use in model construction. It helps -in improving model performance, reducing overfitting, and decreasing -computational cost. - -- Filter methods - -- Wrapper methods - -- Embedded methods - -**Filter Methods** - -Filter methods apply statistical measures to score the relevance of -features. They are computationally efficient and independent of any -machine learning algorithms. - -Examples: - -1. Correlation Coefficient -2. Chi-Square Test -3. ANOVA - -**Wrapper Methods** - -Wrapper methods evaluate the performance of a subset of features using a -specific machine learning algorithm. They are more computationally -intensive compared to filter methods. - -Examples: - -1. Forward Selection -2. Backward Elimination -3. Recursive Feature Elimination (RFE) - -**Embedded Methods** - -Embedded methods perform feature selection as part of the model training -process. They include methods like regularization and tree-based -methods. - -Examples: - -1. Lasso (L1 Regularization) -2. Ridge (L2 Regularization) -3. Decision Trees diff --git a/docs/python/getting-started-py.md b/docs/python/getting-started-py.md deleted file mode 100644 index 80fa0f98c..000000000 --- a/docs/python/getting-started-py.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -id: getting-started-with-python -title: Getting Started with Python -sidebar_label: Getting Started -sidebar_position: 2 -tags: [python] -description: In this tutorial, ---- - - -Here’s a basic guide to get you started with Python: - -## Install Python - -First, you need to install Python on your computer. To install Python on your computer, follow these steps: - -1.Download Python: Go to the official Python website at https://www.python.org/. On the homepage, you will see a “Downloads” section. Click on the “Download Python” button. -![alt text](image-1.png) - -2.Choose the Version: You will be directed to a page where you can choose the version of Python you want to download. Python usually has two main versions available: Python 3. Python 3 is the recommended version. Click on the appropriate version for your operating system (Windows, macOS, or Linux). - -3.Add Python to PATH (Optional): On Windows, you may be given the option to add Python to your system’s PATH environment variable. This makes it easier to run Python from the command line. If you’re not sure, it’s usually safe to select this option. - -4.Install Python: Click the “Install Now” button to begin the installation. The installer will copy the necessary files to your computer. -![alt text](image-2.png) - -5.Verify the Installation: After the installation is complete, you can verify that Python was installed correctly by opening a command prompt (on Windows) or a terminal (on macOS or Linux) and typing python --version. This should display the version of Python you installed. - -That’s it! Python should now be installed on your computer, and you’re ready to start using Python. - -## Setting up a Python Development Environment -An IDE makes coding easier. Popular choices include PyCharm, Visual Studio Code, and Jupyter Notebook. Install one and set it up for Python development. Or you can also use an online Python IDE. - -## Create and Run your First Python Program -For the first program, we will try to print a very simple message “Hello World” in Python, the code for which is given below: - -Once you have Python installed, you can run the program by following these steps: - -- Open a text editor (e.g., Notepad on Windows, TextEdit on macOS, or any code editor like VS Code, PyCharm, etc.). -- Copy the code above and paste it into the text editor. -- Save the file with a .py extension (e.g., hello_world.py). -- Open a terminal or command prompt. -- Navigate to the directory where you saved the file using the cd command (e.g., cd path/to/your/directory). -- Run the program by typing python hello_world.py and pressing Enter. - -You should see the output “Hello, World!” printed in the terminal. - -```python title="hello.py" -# Print a message to the console -print("Hello, World!") # Output: Hello, World! - -# Define a variable and print its value -message = "Hello, Python!" -print(message) # Output: Hello, Python! - -``` - diff --git a/docs/python/image-1.png b/docs/python/image-1.png deleted file mode 100644 index 7bd7d4848..000000000 Binary files a/docs/python/image-1.png and /dev/null differ diff --git a/docs/python/image-2.png b/docs/python/image-2.png deleted file mode 100644 index e2e99166d..000000000 Binary files a/docs/python/image-2.png and /dev/null differ diff --git a/docs/python/image.png b/docs/python/image.png deleted file mode 100644 index 3a0467067..000000000 Binary files a/docs/python/image.png and /dev/null differ diff --git a/docs/python/intro-py.md b/docs/python/intro-py.md deleted file mode 100644 index 9fb0a1a92..000000000 --- a/docs/python/intro-py.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -id: intro-py -title: Introduction to Python -sidebar_label: Introduction to Python -sidebar_position: 1 -tags: [python, programming, language, introduction, syntax, features, applications, libraries, community, open-source, object-oriented, interpreted, cross-platform, scalable] -description: In this tutorial, we will learn about Python, its features, syntax, applications, libraries, and community support. ---- -![pyhton-intro](image.png) - -Python was created by Guido van Rossum and first released in 1991. Python is an open-source language, which means that the source code is freely available for anyone to use, modify, and distribute. Python has a large and active community of developers who contribute to the language and its ecosystem of libraries and tools. - -## What is Python? - -Python is a high-level, interpreted, and general-purpose programming language. Python is designed to be easy to read and write, and its simple syntax makes it a great language for beginners. Python is a versatile language that can be used for web development, data analysis, artificial intelligence, scientific computing, and more. - -Python is known for its readability and simplicity, which makes it a great language for beginners to learn. Python code is easy to read and write, which can help new programmers focus on learning programming concepts rather than getting bogged down in complex syntax. - -Python is an interpreted language, which means that the code is executed line by line by an interpreter. This makes it easy to write and test code quickly, without the need to compile the code before running it. - -## Why Learn Python? - -Python is a popular language for a variety of reasons: - -- **Easy to Learn**: Python has a simple and readable syntax that makes it easy to learn and write code. -- **Versatile**: Python can be used for a wide range of applications, including web development, data analysis, artificial intelligence, scientific computing, and more. -- **Large Community**: Python has a large and active community of developers who contribute to the language and its ecosystem of libraries and tools. -- **Open Source**: Python is an open-source language, which means that the source code is freely available for anyone to use, modify, and distribute. -- **High Demand**: Python is one of the most popular programming languages in the world, and there is a high demand for Python developers in the job market. -- **Object-Oriented**: Python is an object-oriented language, which means that it supports the concepts of classes and objects, making it easy to write modular and reusable code. -- **Interpreted**: Python is an interpreted language, which means that the code is executed line by line by an interpreter, making it easy to write and test code quickly. -- **Cross-Platform**: Python is a cross-platform language, which means that it can run on multiple operating systems, including Windows, macOS, and Linux. -- **Extensive Libraries**: Python has a large standard library that provides support for a wide range of tasks, as well as a vast ecosystem of third-party libraries and tools. -- **Scalable**: Python is a scalable language that can be used for small scripts as well as large applications. -- **Community Support**: Python has a large and active community of developers who provide support and resources for learning and using the language. - -## What can python do? - -Python is a versatile language that can be used for a wide range of applications, including: - -- **Web Development**: Python can be used to build web applications using frameworks like Django and Flask. -- **Data Analysis**: Python is a popular language for data analysis and visualization, with libraries like NumPy, pandas, and Matplotlib. -- **Artificial Intelligence**: Python is widely used in artificial intelligence and machine learning, with libraries like TensorFlow, Keras, and scikit-learn. -- **Scientific Computing**: Python is used in scientific computing and research, with libraries like SciPy and SymPy. -- **Automation**: Python can be used to automate repetitive tasks, such as web scraping, file processing, and data analysis. -- **Game Development**: Python can be used to create games using libraries like Pygame and Panda3D. -- **Desktop Applications**: Python can be used to create desktop applications using libraries like Tkinter and PyQt. -- **Mobile Applications**: Python can be used to create mobile applications using frameworks like Kivy and BeeWare. -- **Internet of Things (IoT)**: Python can be used to build IoT applications using libraries like MicroPython and CircuitPython. -- **Web Scraping**: Python can be used to extract data from websites using libraries like BeautifulSoup and Scrapy. -- **Networking**: Python can be used to build network applications using libraries like Twisted and Scapy. -- **Databases**: Python can be used to interact with databases using libraries like SQLAlchemy and psycopg2. -- **Testing**: Python can be used to write automated tests using libraries like unittest and pytest. -- **Security**: Python can be used to build security tools and applications, such as penetration testing tools and encryption libraries. -- **Education**: Python is a popular language for teaching programming and computer science, with resources like the Python Software Foundation and Codecademy. - -## Basic Syntax of Python - -Python has a simple and readable syntax that makes it easy to learn and write code. Here are some basic examples of Python syntax: - -```python title="hello.py" -# Print a message to the console -print("Hello, World!") # Output: Hello, World! - -# Define a variable and print its value -message = "Hello, Python!" -print(message) # Output: Hello, Python! - -# Define a function and call it -def greet(name): - print("Hello, " + name + "!") -greet("Python") # Output: Hello, Python! -``` - -In the example above, we define a variable `message` with the value `"Hello, Python!"` and print it to the console. We also define a function `greet` that takes a `name` parameter and prints a greeting message to the console. - -## Conclusion - -Python is a versatile and easy-to-learn language that can be used for a wide range of applications. Python's simple syntax and readability make it a great language for beginners to learn, while its powerful features and extensive libraries make it a popular choice for experienced developers. Whether you're interested in web development, data analysis, artificial intelligence, or scientific computing, Python has something to offer for everyone. \ No newline at end of file diff --git a/docs/python/json.md b/docs/python/json.md deleted file mode 100644 index 0c491943f..000000000 --- a/docs/python/json.md +++ /dev/null @@ -1,408 +0,0 @@ ---- -id: json -title: JSON with Python -sidebar_label: JSON with Python -sidebar_position: 3 -tags: [python, programming, language, introduction, json, features, applications, libraries, community, open-source, object-oriented, interpreted, cross-platform, scalable] -description: In this tutorial, we will learn about JSON and JSON with Python with deep detais of JSON ---- - -# Working with JSON in Python - -JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Python provides a built-in module called `json` for working with JSON data. In this tutorial, we will explore various aspects of working with JSON in Python, including parsing, serializing, deserializing, and handling complex data structures. - -## Introduction to JSON - -JSON is a text format for storing and exchanging data. JSON data is represented as key-value pairs, similar to Python dictionaries. Here is an example of a JSON object: - -```json -{ - "name": "John Doe", - "age": 30, - "isStudent": false, - "courses": ["Math", "Science", "History"], - "address": { - "street": "123 Main St", - "city": "Anytown", - "state": "CA" - } -} -``` - -## Parsing JSON in Python - -To parse JSON data in Python, we use the `json.loads()` method, which converts a JSON string into a Python dictionary. - -### Example: - -```python -import json - -json_data = ''' -{ - "name": "John Doe", - "age": 30, - "isStudent": false, - "courses": ["Math", "Science", "History"], - "address": { - "street": "123 Main St", - "city": "Anytown", - "state": "CA" - } -} -''' - -data = json.loads(json_data) - -print(data) -print(data['name']) # Output: John Doe -``` - -## Serializing Data to JSON - -To convert Python objects into JSON strings, we use the `json.dumps()` method. - -### Example: - -```python -import json - -data = { - "name": "John Doe", - "age": 30, - "isStudent": False, - "courses": ["Math", "Science", "History"], - "address": { - "street": "123 Main St", - "city": "Anytown", - "state": "CA" - } -} - -json_data = json.dumps(data) - -print(json_data) -``` - -## Deserializing JSON to Python Objects - -Deserializing is the process of converting a JSON string back into a Python object. We use the `json.loads()` method for this purpose. - -### Example: - -```python -import json - -json_data = ''' -{ - "name": "John Doe", - "age": 30, - "isStudent": false, - "courses": ["Math", "Science", "History"], - "address": { - "street": "123 Main St", - "city": "Anytown", - "state": "CA" - } -} -''' - -data = json.loads(json_data) - -print(data) -``` - -## Working with Complex Data Structures - -JSON can represent complex data structures such as nested dictionaries and lists. Let's see how to work with these structures in Python. - -### Example: - -```python -import json - -json_data = ''' -{ - "students": [ - { - "name": "John Doe", - "age": 30, - "isStudent": false, - "courses": ["Math", "Science", "History"], - "address": { - "street": "123 Main St", - "city": "Anytown", - "state": "CA" - } - }, - { - "name": "Jane Smith", - "age": 25, - "isStudent": true, - "courses": ["English", "Art", "Biology"], - "address": { - "street": "456 Elm St", - "city": "Othertown", - "state": "NY" - } - } - ] -} -''' - -data = json.loads(json_data) - -students = data['students'] -for student in students: - print(f"Name: {student['name']}, Courses: {', '.join(student['courses'])}") -``` - -## JSON Encoding and Decoding Custom Objects - -Sometimes, you may need to serialize and deserialize custom Python objects. To handle this, you can define custom encoder and decoder classes. - -### Example: - -```python -import json - -class Person: - def __init__(self, name, age, city): - self.name = name - self.age = age - self.city = city - -class PersonEncoder(json.JSONEncoder): - def default(self, obj): - if isinstance(obj, Person): - return {'name': obj.name, 'age': obj.age, 'city': obj.city} - return super().default(obj) - -def person_decoder(dct): - if 'name' in dct and 'age' in dct and 'city' in dct: - return Person(dct['name'], dct['age'], dct['city']) - return dct - -person = Person("John Doe", 30, "Anytown") - -json_data = json.dumps(person, cls=PersonEncoder) -print(json_data) - -person_obj = json.loads(json_data, object_hook=person_decoder) -print(f"Name: {person_obj.name}, Age: {person_obj.age}, City: {person_obj.city}") -``` - -## Pretty Printing JSON - -To make JSON data more readable, you can use the `indent` parameter of the `json.dumps()` method. - -### Example: - -```python -import json - -data = { - "name": "John Doe", - "age": 30, - "isStudent": False, - "courses": ["Math", "Science", "History"], - "address": { - "street": "123 Main St", - "city": "Anytown", - "state": "CA" - } -} - -json_data = json.dumps(data, indent=4) -print(json_data) -``` - -## Reading and Writing JSON Files - -You can read JSON data from a file and write JSON data to a file using `json.load()` and `json.dump()` methods, respectively. - -### Example (Reading JSON from a file): - -```python -import json - -with open('data.json', 'r') as file: - data = json.load(file) - -print(data) -``` - -### Example (Writing JSON to a file): - -```python -import json - -data = { - "name": "John Doe", - "age": 30, - "isStudent": False, - "courses": ["Math", "Science", "History"], - "address": { - "street": "123 Main St", - "city": "Anytown", - "state": "CA" - } -} - -with open('data.json', 'w') as file: - json.dump(data, file, indent=4) -``` - -## Handling JSON Errors - -When working with JSON data, errors can occur. It is important to handle these errors to ensure your program runs smoothly. - -### Example: - -```python -import json - -invalid_json_data = ''' -{ - "name": "John Doe", - "age": 30, - "isStudent": false, - "courses": ["Math", "Science", "History"], - "address": { - "street": "123 Main St", - "city": "Anytown", - "state": "CA" -} -''' - -try: - data = json.loads(invalid_json_data) -except json.JSONDecodeError as e: - print(f"JSONDecodeError: {e}") -``` - -## JSON and APIs - -JSON is widely used in APIs to exchange data between servers and clients. Python provides libraries like `requests` to work with APIs. - -### Example (Fetching JSON data from an API): - -```python -import requests -import json - -url = 'https://api.example.com/data' -response = requests.get(url) - -if response.status_code == 200: - data = response.json() - print(data) -else: - print(f"Failed to retrieve data: {response.status_code}") -``` - -## Advanced Topics - -### JSONPath - -JSONPath is a query language for JSON, similar to XPath for XML. It allows you to extract specific data from JSON documents. - -### Example (Using JSONPath): - -```python -import json -import jsonpath_ng - -json_data = ''' -{ - "store": { - "book": [ - {"category": "fiction", "title": "The Great Gatsby"}, - {"category": "fiction", "title": "1984"}, - {"category": "science", "title": "A Brief History of Time"} - ] - } -} -''' - -data = json.loads(json_data) - -jsonpath_expr = jsonpath_ng.parse('$.store.book[*].title') -titles = [match.value for match in - - jsonpath_expr.find(data)] - -print(titles) # Output: ['The Great Gatsby', '1984', 'A Brief History of Time'] -``` - -### JSON Schema - -JSON Schema is a powerful tool for validating the structure and content of JSON data. - -### Example (Using JSON Schema): - -```python -import json -import jsonschema -from jsonschema import validate - -json_data = ''' -{ - "name": "John Doe", - "age": 30, - "isStudent": false -} -''' - -schema = { - "type": "object", - "properties": { - "name": {"type": "string"}, - "age": {"type": "number"}, - "isStudent": {"type": "boolean"} - }, - "required": ["name", "age", "isStudent"] -} - -data = json.loads(json_data) - -try: - validate(instance=data, schema=schema) - print("JSON data is valid") -except jsonschema.exceptions.ValidationError as e: - print(f"JSON data is invalid: {e}") -``` - -### JSON Web Tokens (JWT) - -JWT is a compact, URL-safe means of representing claims to be transferred between two parties. Python libraries like `PyJWT` can be used to work with JWTs. - -### Example (Using JWT): - -```python -import jwt -import datetime - -payload = { - 'user_id': 123, - 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) -} -secret = 'my_secret_key' -token = jwt.encode(payload, secret, algorithm='HS256') - -print(f"Encoded JWT: {token}") - -try: - decoded_payload = jwt.decode(token, secret, algorithms=['HS256']) - print(f"Decoded payload: {decoded_payload}") -except jwt.ExpiredSignatureError: - print("Token has expired") -except jwt.InvalidTokenError: - print("Invalid token") -``` - -## Conclusion - -In this tutorial, we covered various aspects of working with JSON in Python, including parsing, serializing, deserializing, handling complex data structures, encoding and decoding custom objects, pretty printing, reading and writing JSON files, handling errors, and working with APIs. We also explored advanced topics like JSONPath, JSON Schema, and JSON Web Tokens (JWT). - -JSON is a versatile and widely used format for data interchange, and Python's `json` module provides powerful tools for working with JSON data. By mastering these techniques, you can effectively handle JSON data in your Python applications. diff --git a/docs/python/loops.md b/docs/python/loops.md deleted file mode 100644 index 1609395ae..000000000 --- a/docs/python/loops.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -id: loops -title: Python Loops -sidebar_label: Loops in python -sidebar_position: 7 -tags: [python, loops] ---- - -# Python Loops - -Python has two primitive loop commands: - -- while loops -- for loops - -## The while Loop - -With the `while` loop, we can execute a set of statements as long as a condition is true. - -### Example - -```python -i = 1 -while i < 6: - print(i) - i += 1 -``` - -The `while` loop requires relevant variables to be ready, in this example we need to define an indexing variable, `i`, which we set to 1. - -### The break Statement - -With the `break` statement, we can stop the loop even if the `while` condition is true. - -#### Example - -```python -i = 1 -while i < 6: - print(i) - if i == 3: - break - i += 1 -``` - -### The continue Statement - -With the `continue` statement, we can stop the current iteration and continue with the next. - -#### Example - -```python -i = 0 -while i < 6: - i += 1 - if i == 3: - continue - print(i) -``` - -### The else Statement - -With the `else` statement, we can run a block of code once when the condition no longer is true. - -#### Example - -```python -i = 1 -while i < 6: - print(i) - i += 1 -else: - print("i is no longer less than 6") -``` - -## Python For Loops - -A `for` loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). - -### Example - -```python -fruits = ["apple", "banana", "cherry"] -for x in fruits: - print(x) -``` - -The `for` loop does not require an indexing variable to be set beforehand. - -### Looping Through a String - -Even strings are iterable objects; they contain a sequence of characters. - -#### Example - -```python -for x in "banana": - print(x) -``` - -### The break Statement - -With the `break` statement, we can stop the loop before it has looped through all the items. - -#### Example - -```python -fruits = ["apple", "banana", "cherry"] -for x in fruits: - print(x) - if x == "banana": - break -``` - -### The continue Statement - -With the `continue` statement, we can stop the current iteration of the loop and continue with the next. - -#### Example - -```python -fruits = ["apple", "banana", "cherry"] -for x in fruits: - if x == "banana": - continue - print(x) -``` - -### The range() Function - -To loop through a set of code a specified number of times, we can use the `range()` function. The `range()` function returns a sequence of numbers starting from 0 by default, and increments by 1 (by default), and ends at a specified number. - -#### Example - -```python -for x in range(6): - print(x) -``` - -### Else in For Loop - -The `else` keyword in a `for` loop specifies a block of code to be executed when the loop is finished. - -#### Example - -```python -for x in range(6): - print(x) -else: - print("Finally finished!") -``` - -### Nested Loops - -A nested loop is a loop inside a loop. - -![nested loop](https://geekpython.in/wp-content/uploads/2023/08/nested-for-loop.png) -#### Example - -```python -adj = ["red", "big", "tasty"] -fruits = ["apple", "banana", "cherry"] - -for x in adj: - for y in fruits: - print(x, y) -``` - -### The pass Statement - -`for` loops cannot be empty, but if you, for some reason, have a `for` loop with no content, put in the `pass` statement to avoid getting an error. - -#### Example - -```python -for x in [0, 1, 2]: - pass -``` - -This documentation covers the basics of Python loops, including `while` and `for` loops, along with control flow statements like `break`, `continue`, and `else`. Examples are provided for each concept to illustrate their usage effectively. \ No newline at end of file diff --git a/docs/python/math-in-python.md b/docs/python/math-in-python.md deleted file mode 100644 index 55799e5b8..000000000 --- a/docs/python/math-in-python.md +++ /dev/null @@ -1,255 +0,0 @@ ---- -id: math-in-python -title: Math with Python -sidebar_label: Math with Python -sidebar_position: 4 -tags: [python, programming, language, introduction, math, features, applications, libraries, community, open-source, object-oriented, interpreted, cross-platform, scalable] -description: In this tutorial, we will learn about math and math operations with Python, with deep details of the math module and its functions. ---- - -# Working with Math in Python - -Python is known for its simplicity and versatility, which extends to its handling of mathematical operations. Python provides a built-in module called `math` for performing mathematical functions. In this tutorial, we will explore various aspects of working with the `math` module in Python, including basic arithmetic, advanced functions, trigonometry, and more. - -## Introduction to the Math Module - -The `math` module provides access to mathematical functions and constants defined by the C standard. To use these functions, you need to import the module. - -```python -import math -``` - -The `math` module includes a wide variety of mathematical functions, from basic arithmetic to complex operations. - -## Basic Arithmetic Functions - -The `math` module provides several functions for basic arithmetic operations, such as addition, subtraction, multiplication, and division. - -### Example: - -```python -import math - -result_add = math.fsum([1.1, 2.2, 3.3]) -result_subtract = math.fabs(-10) -result_multiply = math.prod([2, 3, 4]) -result_divide = math.ceil(7.5) - -print(f"Sum: {result_add}") # Output: 6.6 -print(f"Absolute: {result_subtract}") # Output: 10.0 -print(f"Product: {result_multiply}") # Output: 24 -print(f"Ceiling: {result_divide}") # Output: 8 -``` - -## Power and Logarithmic Functions - -The `math` module provides functions for power and logarithmic calculations. - -### Example: - -```python -import math - -result_power = math.pow(2, 3) # 2^3 -result_sqrt = math.sqrt(16) # Square root - -print(f"Power: {result_power}") # Output: 8.0 -print(f"Square Root: {result_sqrt}") # Output: 4.0 - -result_log = math.log(100, 10) # log base 10 -result_log2 = math.log2(8) # log base 2 -result_log10 = math.log10(100) # log base 10 - -print(f"Log base 10: {result_log}") # Output: 2.0 -print(f"Log base 2: {result_log2}") # Output: 3.0 -print(f"Log base 10: {result_log10}") # Output: 2.0 -``` - -## Trigonometric Functions - -The `math` module provides functions for trigonometric calculations, including sine, cosine, tangent, and their inverses. - -### Example: - -```python -import math - -result_sin = math.sin(math.pi / 2) # Sine of 90 degrees -result_cos = math.cos(0) # Cosine of 0 degrees -result_tan = math.tan(math.pi / 4) # Tangent of 45 degrees - -print(f"Sine: {result_sin}") # Output: 1.0 -print(f"Cosine: {result_cos}") # Output: 1.0 -print(f"Tangent: {result_tan}") # Output: 1.0 - -result_asin = math.asin(1) # Inverse sine -result_acos = math.acos(1) # Inverse cosine -result_atan = math.atan(1) # Inverse tangent - -print(f"Inverse Sine: {result_asin}") # Output: 1.5707963267948966 -print(f"Inverse Cosine: {result_acos}") # Output: 0.0 -print(f"Inverse Tangent: {result_atan}") # Output: 0.7853981633974483 -``` - -## Hyperbolic Functions - -The `math` module also includes hyperbolic functions, which are analogs of the trigonometric functions but for hyperbolas. - -### Example: - -```python -import math - -result_sinh = math.sinh(1) # Hyperbolic sine -result_cosh = math.cosh(1) # Hyperbolic cosine -result_tanh = math.tanh(1) # Hyperbolic tangent - -print(f"Hyperbolic Sine: {result_sinh}") # Output: 1.1752011936438014 -print(f"Hyperbolic Cosine: {result_cosh}") # Output: 1.5430806348152437 -print(f"Hyperbolic Tangent: {result_tanh}") # Output: 0.7615941559557649 - -result_asinh = math.asinh(1) # Inverse hyperbolic sine -result_acosh = math.acosh(1) # Inverse hyperbolic cosine -result_atanh = math.atanh(0.5) # Inverse hyperbolic tangent - -print(f"Inverse Hyperbolic Sine: {result_asinh}") # Output: 0.881373587019543 -print(f"Inverse Hyperbolic Cosine: {result_acosh}") # Output: 0.0 -print(f"Inverse Hyperbolic Tangent: {result_atanh}") # Output: 0.5493061443340548 -``` - -## Special Functions - -The `math` module includes several special functions for mathematical operations such as gamma, factorial, and others. - -### Example: - -```python -import math - -result_gamma = math.gamma(5) # Gamma function - -print(f"Gamma: {result_gamma}") # Output: 24.0 - -result_factorial = math.factorial(5) # Factorial function - -print(f"Factorial: {result_factorial}") # Output: 120 - -result_erf = math.erf(1) # Error function - -print(f"Error Function: {result_erf}") # Output: 0.8427007929497148 -``` - -## Constants - -The `math` module provides several mathematical constants, such as `pi` and `e`. - -### Example: - -```python -import math - -print(f"Pi: {math.pi}") # Output: 3.141592653589793 -print(f"Euler's number: {math.e}") # Output: 2.718281828459045 -``` - -## Working with Degrees and Radians - -The `math` module provides functions to convert between degrees and radians. - -### Example: - -```python -import math - -degrees = 180 -radians = math.radians(degrees) -print(f"Degrees to Radians: {radians}") # Output: 3.141592653589793 - -radians = math.pi -degrees = math.degrees(radians) -print(f"Radians to Degrees: {degrees}") # Output: 180.0 -``` - -## Complex Numbers - -Python has a built-in type for complex numbers, but the `cmath` module is specifically designed for complex mathematical functions. - -### Example: - -```python -import cmath - -complex_num = 1 + 2j - -result_sqrt = cmath.sqrt(complex_num) # Square root of a complex number - -print(f"Square Root: {result_sqrt}") # Output: (1.272019649514069+0.7861513777574233j) - - -result_sin = cmath.sin(complex_num) # Sine of a complex number - -print(f"Sine: {result_sin}") # Output: (3.165778513216168+1.959601041421606j) -``` - -## Working with Fractions - -The `fractions` module provides support for rational number arithmetic. - -### Example: - -```python -from fractions import Fraction - - -frac1 = Fraction(1, 2) # 1/2 -frac2 = Fraction(3, 4) # 3/4 - - -result_add = frac1 + frac2 -result_subtract = frac1 - frac2 -result_multiply = frac1 * frac2 -result_divide = frac1 / frac2 - -print(f"Addition: {result_add}") # Output: 5/4 -print(f"Subtraction: {result_subtract}") # Output: -1/4 -print(f"Multiplication: {result_multiply}") # Output: 3/8 -print(f"Division: {result_divide}") # Output: 2/3 -``` - -## Statistics Module - -Python's `statistics` module provides functions for calculating mathematical statistics of numeric data. - -### Example: - -```python -import statistics - -data = [1, 2, 2, 3, - -4, 7, 9] - - -mean = statistics.mean(data) -print(f"Mean: {mean}") # Output: 4.0 - - -median = statistics.median(data) -print(f"Median: {median}") # Output: 3 - - -mode = statistics.mode(data) -print(f"Mode: {mode}") # Output: 2 - - -stdev = statistics.stdev(data) -print(f"Standard Deviation: {stdev}") # Output: 2.9277002188455996 -``` - -## Conclusion - -In this tutorial, we covered various aspects of working with math in Python, including basic arithmetic, power and logarithmic functions, trigonometry, hyperbolic functions, special functions, constants, degrees and radians, complex numbers, fractions, and statistics. Python's `math` module provides a robust set of functions for mathematical operations, making it a powerful tool for scientific computing and data analysis. - -By mastering these techniques, you can effectively handle a wide range of mathematical computations in your Python applications. - -This concludes our in-depth tutorial on working with math in Python. Happy coding! \ No newline at end of file diff --git a/docs/python/pip.md b/docs/python/pip.md deleted file mode 100644 index d0546c079..000000000 --- a/docs/python/pip.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -id: pip -title: Working with pip in Python -sidebar_label: Working with pip in Python -sidebar_position: 5 -tags: [python, programming, language, introduction, pip, features, applications, libraries, community, open-source, package-management, installation] -description: In this tutorial, we will learn about pip, the package installer for Python, with deep details of its usage and features. ---- - -# Working with pip in Python - -`pip` is the package installer for Python, allowing you to install and manage additional libraries and dependencies that are not included in the Python standard library. In this tutorial, we will explore various aspects of working with `pip`, including installing packages, managing dependencies, creating and using virtual environments, and more. - -Introduction to pip - -`pip` is a command-line tool that allows you to install and manage Python packages. It simplifies the process of installing and managing third-party libraries, making it easier to develop and deploy Python applications. - -Installing pip - -Python 3.4 and later versions come with `pip` pre-installed. However, if you need to install `pip` manually, you can do so by downloading `get-pip.py` and running it using Python. - -```bash -curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py -python get-pip.py -``` - -Installing Packages with pip - -You can install packages from the Python Package Index (PyPI) using the `pip install` command. - -```bash -pip install package_name -``` - -You can also install a specific version of a package. - -```bash -pip install package_name==version_number -``` - -Upgrading Packages - -To upgrade a package to the latest version, use the `pip install --upgrade` command. - -```bash -pip install --upgrade package_name -``` - -Uninstalling Packages - -To uninstall a package, use the `pip uninstall` command. - -```bash -pip uninstall package_name -``` - -Listing Installed Packages - -To list all installed packages, use the `pip list` command. - -```bash -pip list -``` - -Showing Package Information - -To show detailed information about an installed package, use the `pip show` command. - -```bash -pip show package_name -``` - -Freezing Package Versions - -To generate a list of installed packages and their versions, use the `pip freeze` command. This is useful for creating `requirements.txt` files. - -```bash -pip freeze > requirements.txt -``` - -Installing Packages from a Requirements File - -To install packages listed in a `requirements.txt` file, use the `pip install -r` command. - -```bash -pip install -r requirements.txt -``` - -Creating Virtual Environments - -Virtual environments are isolated environments that allow you to manage dependencies for different projects separately. Use the `venv` module to create virtual environments. - -```bash -python -m venv env_name -``` - -Activating and Deactivating Virtual Environments - -Activate the virtual environment. - -- On Windows: - ```bash - env_name\Scripts\activate - ``` - -- On macOS and Linux: - ```bash - source env_name/bin/activate - ``` - -Deactivate the virtual environment. - -```bash -deactivate -``` - -Installing Packages in a Virtual Environment - -Activate the virtual environment and then use `pip` to install packages. - -```bash -source env_name/bin/activate -pip install package_name -``` - -Searching for Packages - -Use the `pip search` command to search for packages on PyPI. - -```bash -pip search search_term -``` - -Checking for Outdated Packages - -Use the `pip list --outdated` command to list outdated packages. - -```bash -pip list --outdated -``` - -Configuring pip - -You can configure `pip` using a configuration file or environment variables. The configuration file locations vary by platform. - -- On Windows: - ``` - %APPDATA%\pip\pip.ini - ``` - -- On macOS and Linux: - ``` - ~/.pip/pip.conf - ``` - -An example configuration file: - -```ini -[global] -timeout = 60 -index-url = https://pypi.python.org/simple/ -``` - -Using pip with Proxy Servers - -Configure `pip` to use a proxy server. - -```bash -pip install --proxy http://proxy.example.com:8080 package_name -``` - -Using Environment Variables - -Set environment variables to configure `pip` settings. - -```bash -export PIP_INDEX_URL=https://pypi.python.org/simple/ -export PIP_TIMEOUT=60 -``` - -Handling Dependency Conflicts - -To check for dependency conflicts, use the `pip check` command. - -```bash -pip check -``` - -Installing Packages from Source - -Install packages from source code using the `pip install` command with a URL or local path. - -```bash -pip install https://github.com/user/repo/archive/branch.zip -pip install /path/to/package -``` - -Using pip with Git Repositories - -Install packages directly from Git repositories. - -```bash -pip install git+https://github.com/user/repo.git -``` - -Custom Package Indexes - -Configure `pip` to use custom package indexes. - -```bash -pip install --index-url https://custom.pypi.org/simple/ package_name -``` - -Installing Packages in Editable Mode - -Install packages in editable mode during development. - -```bash -pip install -e /path/to/package -``` - -Using pip Tools and Plugins - -Enhance `pip` functionality with tools and plugins like `pip-tools` and `pipenv`. - -- pip-tools: Generate `requirements.txt` files from `requirements.in`. - -```bash -pip install pip-tools -pip-compile requirements.in -``` - -- pipenv: A tool for managing virtual environments and dependencies. - -```bash -pip install pipenv -pipenv install package_name -``` - -Best Practices for Using pip - -- Always use virtual environments to manage dependencies. -- Use `requirements.txt` files to specify dependencies. -- Regularly update packages to their latest versions. -- Handle dependency conflicts promptly. -- Use pip tools and plugins to streamline dependency management. - -Conclusion - -In this tutorial, we explored various aspects of working with `pip` in Python, including installing, upgrading, and uninstalling packages, creating and using virtual environments, managing dependencies, and configuring `pip`. By mastering these techniques, you can effectively manage Python packages and dependencies in your projects. Happy coding! \ No newline at end of file diff --git a/docs/python/resource.md b/docs/python/resource.md deleted file mode 100644 index ec9f3d4d0..000000000 --- a/docs/python/resource.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -id: cpp-further-learning-resources -title: Further Resources for Learning Python -sidebar_label: Further Resources for Learning Python -sidebar_position: 21 -tags: - [ - Python, - Python next steps, - programming, - Python resources, - Python further learning - ] -description: In this tutorial, we'll explore further resources for learning Python. We'll provide a curated list of books, online courses, websites, and communities where you can continue your Python learning journey. You'll discover resources tailored to your skill level, from beginner to advanced, covering various aspects of Python programming, including syntax, data structures, algorithms, and advanced topics such as concurrency and optimization. Whether you're just starting out or looking to deepen your Python expertise, these additional resources will help you enhance your skills and stay updated with the latest developments in the Python community. ---- - -Here is a curated list of resources for learning Python, ranging from beginner to advanced levels. These resources cover various aspects of Python programming, including syntax, data structures, algorithms, and advanced topics like concurrency and optimization. - -### Beginner - -#### Books -1. **["Automate the Boring Stuff with Python" by Al Sweigart](https://automatetheboringstuff.com/)** - - Focuses on practical programming for total beginners. -2. **["Python Crash Course" by Eric Matthes](https://nostarch.com/pythoncrashcourse2e)** - - A hands-on, project-based introduction to Python. - -#### Online Courses -1. **[Coursera: Python for Everybody Specialization by the University of Michigan](https://www.coursera.org/specializations/python)** - - A comprehensive course series for beginners. -2. **[edX: Introduction to Computer Science and Programming Using Python by MIT](https://www.edx.org/course/introduction-to-computer-science-and-programming-using-python)** - - An excellent introduction to programming with Python. - -#### Websites -1. **[Python.org (Official Python Documentation)](https://docs.python.org/3/tutorial/)** - - The official Python website offers tutorials, guides, and extensive documentation. -2. **[W3Schools Python Tutorial](https://www.w3schools.com/python/)** - - Easy-to-follow tutorials covering basic to advanced Python topics. - -#### Communities -1. **[Reddit: r/learnpython](https://www.reddit.com/r/learnpython/)** - - A community for Python learners to ask questions and share resources. -2. **[Python Discord](https://pythondiscord.com/)** - - An active community for discussing Python-related topics and getting help. - -### Intermediate - -#### Books -1. **["Fluent Python" by Luciano Ramalho](https://www.oreilly.com/library/view/fluent-python/9781491946237/)** - - In-depth exploration of Python’s capabilities and idiomatic practices. -2. **["Effective Python: 90 Specific Ways to Write Better Python" by Brett Slatkin](https://effectivepython.com/)** - - Practical advice for improving your Python code. - -#### Online Courses -1. **[Udacity: Intermediate Python Nanodegree](https://www.udacity.com/course/intermediate-python-nanodegree--nd303)** - - Covers more advanced Python topics, including object-oriented programming. -2. **[Pluralsight: Advanced Python](https://www.pluralsight.com/courses/advanced-python)** - - Detailed courses on specific Python libraries and advanced concepts. - -#### Websites -1. **[Real Python](https://realpython.com/)** - - Articles, tutorials, and guides on various Python topics. -2. **[GeeksforGeeks Python Programming Language](https://www.geeksforgeeks.org/python-programming-language/)** - - Tutorials and problem-solving exercises for intermediate learners. - -#### Communities -1. **[Stack Overflow](https://stackoverflow.com/questions/tagged/python)** - - A great place to ask technical questions and find solutions. -2. **[Python Meetup Groups](https://www.meetup.com/topics/python/)** - - Local and virtual meetups for Python enthusiasts. - -### Advanced - -#### Books -1. **["Python Cookbook" by David Beazley and Brian K. Jones](https://www.oreilly.com/library/view/python-cookbook-3rd/9781449357337/)** - - Recipes for advanced Python programming. -2. **["Designing Data-Intensive Applications" by Martin Kleppmann](https://dataintensive.net/)** - - Though not Python-specific, it's invaluable for understanding data-heavy applications. - -#### Online Courses -1. **[Coursera: Applied Data Science with Python Specialization by the University of Michigan](https://www.coursera.org/specializations/data-science-python)** - - Advanced data science techniques using Python. -2. **[edX: Python Data Science by Harvard University](https://www.edx.org/professional-certificate/harvardx-data-science)** - - Covers data science and machine learning using Python. - -#### Websites -1. **[Towards Data Science](https://towardsdatascience.com/)** - - Articles and tutorials on advanced data science topics using Python. -2. **[PyPI (Python Package Index)](https://pypi.org/)** - - Discover and learn about various Python libraries and tools. - -#### Communities -1. **[GitHub](https://github.com/)** - - Explore and contribute to open-source Python projects. -2. **[PyCon](https://us.pycon.org/)** - - Annual Python conferences that offer talks, tutorials, and networking opportunities. - -By leveraging these resources, you can enhance your Python skills and stay updated with the latest developments in the Python community. Happy learning! - - - diff --git a/docusaurus.config.js b/docusaurus.config.js index 187058b8c..12f3fa1bc 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -146,7 +146,7 @@ const config = { JavaScript React TypeScript - Python + Python Tailwind Next