diff --git a/Matrix Operations/__pycache__/adjoint.cpython-312.pyc b/Matrix Operations/__pycache__/adjoint.cpython-312.pyc new file mode 100644 index 00000000..8a3a9ada Binary files /dev/null and b/Matrix Operations/__pycache__/adjoint.cpython-312.pyc differ diff --git a/Matrix Operations/__pycache__/checker.cpython-312.pyc b/Matrix Operations/__pycache__/checker.cpython-312.pyc new file mode 100644 index 00000000..d4ca6adf Binary files /dev/null and b/Matrix Operations/__pycache__/checker.cpython-312.pyc differ diff --git a/Matrix Operations/__pycache__/cofactor.cpython-312.pyc b/Matrix Operations/__pycache__/cofactor.cpython-312.pyc new file mode 100644 index 00000000..72359c94 Binary files /dev/null and b/Matrix Operations/__pycache__/cofactor.cpython-312.pyc differ diff --git a/Matrix Operations/__pycache__/determinant.cpython-312.pyc b/Matrix Operations/__pycache__/determinant.cpython-312.pyc new file mode 100644 index 00000000..5cb070cb Binary files /dev/null and b/Matrix Operations/__pycache__/determinant.cpython-312.pyc differ diff --git a/Matrix Operations/__pycache__/minor.cpython-312.pyc b/Matrix Operations/__pycache__/minor.cpython-312.pyc new file mode 100644 index 00000000..bd13d9e7 Binary files /dev/null and b/Matrix Operations/__pycache__/minor.cpython-312.pyc differ diff --git a/Matrix Operations/__pycache__/transpose.cpython-312.pyc b/Matrix Operations/__pycache__/transpose.cpython-312.pyc new file mode 100644 index 00000000..49e9c9e6 Binary files /dev/null and b/Matrix Operations/__pycache__/transpose.cpython-312.pyc differ diff --git a/Matrix Operations/addition.py b/Matrix Operations/addition.py new file mode 100644 index 00000000..fc8e5dfe --- /dev/null +++ b/Matrix Operations/addition.py @@ -0,0 +1,56 @@ +""" +This program implements matrix addition. + +It includes a function to check if the dimensions of two matrices match, +a function to add two matrices, and a main function to test the matrix +addition function. + +Example: + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + matrix_addition(m1, m2) + [[2, 4, 6], [8, 10, 12], [14, 16, 18]] +""" + +from checker import check_matrix_dimension, print_matrix +import sys + + +def matrix_addition(m1, m2): + """ + This function adds two matrices. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + list of lists: The sum of the two matrices. + + Raises: + sys.exit: If the dimensions of the two matrices do not match. + """ + if check_matrix_dimension(m1, m2) == False: + sys.exit("Matrix dimensions do not match") + + n = len(m1) + m = len(m1[0]) + answer = [[0 for i in range(m)] for j in range(n)] + for i in range(len(m1)): + for j in range(len(m1[i])): + answer[i][j] = m1[i][j] + m2[i][j] + return answer + + +def main(): + """ + This function tests the matrix addition function. + + """ + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print_matrix(matrix_addition(m1, m2)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/adjoint.py b/Matrix Operations/adjoint.py new file mode 100644 index 00000000..23717199 --- /dev/null +++ b/Matrix Operations/adjoint.py @@ -0,0 +1,49 @@ +""" +This module contains a function to calculate the adjoint matrix of a given matrix. + +The adjoint matrix of a matrix is the transpose of its cofactor matrix. + +The module contains the following functions: + +- `adjoint(matrix)`: This function takes a matrix as input and returns its + adjoint matrix. + +The module also contains a main function which tests the adjoint function. + +Example: + matrix = [[1, -1, 2], [2, 3, 5], [1, 0, 3]] + adjoint(matrix) + # Output: + # [[9, 3, -11], [-1, 1, -1], [-3, -1, 5]] +""" + +from checker import print_matrix +from cofactor import cofactor +from transpose import transpose + + +def adjoint(matrix): + """ + This function takes a matrix as input and returns its adjoint matrix. + + Args: + matrix (list of lists): The input matrix. + + Returns: + list of lists: The adjoint matrix of the input matrix. + + Raises: + sys.exit: If the input matrix is not a square matrix. + """ + matrix = transpose(cofactor(matrix)) + return matrix + + +def main(): + m = [[1, -1, 2], [2, 3, 5], [1, 0, 3]] + result = adjoint(m) + print_matrix(result) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/checker.py b/Matrix Operations/checker.py new file mode 100644 index 00000000..3f453f7c --- /dev/null +++ b/Matrix Operations/checker.py @@ -0,0 +1,131 @@ +""" +This program contains functions to validate a matrix, check if two matrices +can be added or multiplied, and check if a matrix is square. It also contains +a function to print a matrix. + +Example: + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m4 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print(check_matrix_dimension(m1, m2)) + print(check_matrix_multiplication(m1, m2)) + print(check_matrix_square(m3)) + print(check_matrix_square(m4)) + print_matrix(m1) + print_matrix(m2) +""" + +def validate_matrix(m): + """ + This function validates a matrix. + + It checks if the 2d array is a valid matrix and if the matrix is a list of + lists. + + Args: + m (list of lists): The matrix to be validated. + + Returns: + bool: True if the matrix is valid, False otherwise. + """ + n = len(m[0]) + for i in range(len(m)): + if len(m[i]) != n: + return False + return True + + +def check_matrix_dimension(m1, m2): + """ + This function checks if two matrices can be added. + + It checks if the two matrices have the same dimensions. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + bool: True if the two matrices can be added, False otherwise. + """ + if (validate_matrix(m1) and validate_matrix(m2)) == False: + return False + n = len(m1) + if (n != len(m2)): + return False + for i in range(n): + if (len(m1[i]) != len(m2[i])): + return False + return True + + +def check_matrix_multiplication(m1, m2): + """ + This function checks if two matrices can be multiplied. + + It checks if the two matrices have the same number of columns as the first + matrix has rows. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + bool: True if the two matrices can be multiplied, False otherwise. + """ + if (validate_matrix(m1) and validate_matrix(m2)) == False: + return False + n = len(m1[0]) + if (n != len(m2)): + return False + return True + + +def check_matrix_square(m): + """ + This function checks if a matrix is square. + + Args: + m (list of lists): The matrix to be checked. + + Returns: + bool: True if the matrix is square, False otherwise. + """ + if validate_matrix(m) == False: + return False + n = len(m) + if (n != len(m[0])): + return False + return True + + +def print_matrix(m): + """ + This function prints a matrix in the terminal for readability. + + Args: + m (list of lists): The matrix to be printed. + """ + for i in range(len(m)): + for j in range(len(m[i])): + print(m[i][j], end=" ") + print() + print() + + +def main(): + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m4 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print(check_matrix_dimension(m1, m2)) + print(check_matrix_multiplication(m1, m2)) + print(check_matrix_square(m3)) + print(check_matrix_square(m4)) + print_matrix(m1) + print_matrix(m2) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/cofactor.py b/Matrix Operations/cofactor.py new file mode 100644 index 00000000..9355bebe --- /dev/null +++ b/Matrix Operations/cofactor.py @@ -0,0 +1,74 @@ +""" +This module contains functions to calculate the cofactor matrix of a given +matrix. + +A cofactor matrix is a matrix where each element is the cofactor of the +corresponding element in the original matrix. The cofactor of an element is +defined as the minor of the element multiplied by (-1) to the power of the sum +of the row and column indices. + +The module contains the following functions: + +- `cofactor(matrix)`: This function takes a matrix as input + and returns its cofactor matrix. + +The module also contains a main function which tests the +`calculate_cofactor_matrix` function. + +Example usage: + matrix = [ + [1, 2, 3], + [0, 4, 5], + [1, 0, 6] + ] + + result = calculate_cofactor_matrix(matrix) + print_matrix(result) +""" + +from checker import print_matrix +from minor import minor +from determinant import determinant + + +def cofactor(matrix): + """ + This function takes a matrix as input and returns its cofactor matrix. + + Args: + matrix (list of lists): The input matrix. + + Returns: + list of lists: The cofactor matrix of the input matrix. + + Raises: + sys.exit: If the input matrix is not a square matrix. + """ + + n = len(matrix) + cofactor_matrix = [] + for i in range(n): + cofactor_row = [] + for j in range(n): + minor_matrix = minor(matrix, i, j) + cofactor_value = ((-1) ** (i + j)) * determinant(minor_matrix) + cofactor_row.append(cofactor_value) + cofactor_matrix.append(cofactor_row) + + return cofactor_matrix + + +def main(): + # Example usage: + matrix = [ + [1, 2, 3], + [0, 4, 5], + [1, 0, 6] + ] + + result = cofactor(matrix) + print_matrix(result) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/determinant.py b/Matrix Operations/determinant.py new file mode 100644 index 00000000..70fe188a --- /dev/null +++ b/Matrix Operations/determinant.py @@ -0,0 +1,61 @@ +""" +This module contains functions to calculate the determinant of a matrix. + +The determinant of a matrix is a scalar value that can be used to describe the +matrix's linear transformation. It can be used to determine the solvability of a +system of linear equations, invertibility of a matrix, and the volume scaling +factor of the linear transformation. + +The module contains the following functions: + +- `determinant(matrix)`: This function takes a matrix as input and returns its + determinant. + +The module also contains a main function which tests the determinant function. + +Example: + matrix = [[1, 2], [2, 9]] + determinant(matrix) + # Output: 7 + +""" +from checker import check_matrix_square +import sys +from minor import minor + +def determinant(matrix): + """ + Calculate the determinant of a matrix. + + Parameters + ---------- + matrix : list of lists + The matrix whose determinant is to be calculated. + + Returns + ------- + int + The determinant of the matrix. + + Raises + ------ + sys.exit + If the matrix is not square. + """ + if not check_matrix_square(matrix): + sys.exit("Matrix is not square") + if len(matrix) == 1: + return matrix[0][0] + if len(matrix) == 2: + return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] + return sum(((-1) ** j) * matrix[0][j] * determinant(minor(matrix, 0, j)) for j in range(len(matrix))) + + + +def main(): + matrix = [[1, 2], [2, 9]] + print(determinant(matrix)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/input.py b/Matrix Operations/input.py new file mode 100644 index 00000000..808defca --- /dev/null +++ b/Matrix Operations/input.py @@ -0,0 +1,59 @@ +""" +This program asks the user to input a matrix and prints it back to the user. + +It asks the user how many rows they want in their matrix and then asks the user +to input the elements of the matrix one row at a time. If the user inputs a +matrix that is not valid, the program will raise a SystemExit exception with +the message "Matrix is not valid". + +The program will then print out the matrix that the user input with the message +"Here's your matrix: \n". + +Example: + $ python input.py + How many rows in your matrix? 3 + 1 2 3 + 4 5 6 + 7 8 9 + Here's your matrix: + [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + +""" + +from checker import print_matrix, validate_matrix +import sys + + +def input_matrix(): + """ + Ask the user to input a matrix. + + The function asks the user how many rows they want in their matrix and then + asks the user to input the elements of the matrix one row at a time. If the + user inputs a matrix that is not valid, the function will raise a SystemExit + exception with the message "Matrix is not valid". + + Returns: + list of lists: The matrix that the user input. + """ + m = [list(map(int, input().split())) for _ in range(int(input("How many rows in your matrix?")))] + if validate_matrix(m) == False: + sys.exit("Matrix is not valid") + return m + + +def main(): + """ + The main function of the program. + + The function asks the user to input a matrix and then prints out the matrix + that the user input with the message "Here's your matrix: \n". + """ + m = input_matrix() + print("Here's your matrix: \n") + print_matrix(m) + + +if __name__ == "__main__": + main() + diff --git a/Matrix Operations/inverse.py b/Matrix Operations/inverse.py new file mode 100644 index 00000000..4ebf2d34 --- /dev/null +++ b/Matrix Operations/inverse.py @@ -0,0 +1,48 @@ +""" +The inverse of a matrix is a matrix that when multiplied with the original +matrix gives the identity matrix. The inverse of a matrix is calculated using +the adjoint matrix and the determinant of the matrix. The adjoint matrix is the +transpose of the cofactor matrix and the determinant is the sum of the products +of the elements of the matrix and their corresponding cofactors. + +The function first calculates the determinant of the matrix. If the determinant +is zero, the function raises a ValueError because the inverse of a matrix with +zero determinant does not exist. The function then calculates the adjoint matrix +and divides each element of the adjoint matrix by the determinant to get the +inverse matrix. +""" +from checker import print_matrix +from adjoint import adjoint +from determinant import determinant +import sys + +def inverse(matrix): + """ + Calculate the inverse of a matrix. + + Args: + matrix (list of lists): The matrix whose inverse is to be calculated. + + Returns: + list of lists: The inverse of the input matrix. + + Raises: + sys.exit: If the matrix is not square or has zero determinant. + """ + det = determinant(matrix) + if det == 0: + sys.exit("Determinant of the matrix is zero and hence inverse matrix does not exist") + matrix = adjoint(matrix) + for i in range(len(matrix)): + for j in range(len(matrix[i])): + matrix[i][j] = matrix[i][j] / det + return matrix + + +def main(): + matrix = [[2, 7, 9], [3, 10, 2], [14, 6, 15]] + print_matrix(inverse(matrix)) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Matrix Operations/matrix.py b/Matrix Operations/matrix.py new file mode 100644 index 00000000..4e5d6733 --- /dev/null +++ b/Matrix Operations/matrix.py @@ -0,0 +1,60 @@ +# matrix.py +''' + The purpose of this program is to give easy access to all the functions of + the program in the parent directory. +''' + +from addition import matrix_addition +from subtraction import matrix_subtraction +from multiplication import matrix_multiplication +from transpose import transpose as transpose_matrix +from rotate import rotate as rotate_matrix +from cofactor import cofactor as calculate_cofactor +from determinant import determinant as calculate_determinant +from adjoint import adjoint as calculate_adjoint +from inverse import inverse as calculate_inverse +from swap import swap_row, swap_column +from sum import matrix_sum, trace, sum_secondary_diagonal + +def add_matrices(matrix1, matrix2): + return matrix_addition(matrix1, matrix2) + +def subtract_matrices(matrix1, matrix2): + + return matrix_subtraction(matrix1, matrix2) + +def multiply_matrices(matrix1, matrix2): + return matrix_multiplication(matrix1, matrix2) + +def transpose(matrix): + return transpose_matrix(matrix) + +def rotate(matrix, angle): + return rotate_matrix(matrix, angle) + +def cofactor(matrix): + return calculate_cofactor(matrix) + +def determinant(matrix): + return calculate_determinant(matrix) + +def adjoint(matrix): + return calculate_adjoint(matrix) + +def inverse(matrix): + return calculate_inverse(matrix) + +def swap_row(matrix, i, j): + return swap_row(matrix, i, j) + +def swap_column(matrix, i, j): + return swap_column(matrix, i, j) + +def sum_matrix(matrix): + return matrix_sum(matrix) + +def matrix_trace(matrix): + return trace(matrix) + +def secondary_diagonal_sum(matrix): + return sum_secondary_diagonal(matrix) \ No newline at end of file diff --git a/Matrix Operations/minor.py b/Matrix Operations/minor.py new file mode 100644 index 00000000..07e96207 --- /dev/null +++ b/Matrix Operations/minor.py @@ -0,0 +1,54 @@ +""" +This module contains a function to calculate the minor matrix of a given matrix. + +The function takes a matrix and two indices as arguments and returns the minor +matrix of the given matrix at the given indices. + +The minor matrix is a matrix that is formed by removing the row and column at the +given indices from the given matrix. + +The module also contains a main function which tests the minor function. + +Example: + matrix = [[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12], [13, 14, 15, 16]] + i = 1 + j = 1 + minor(matrix, i-1, j-1) + # Output: + # [[1, 3, 10], [7, 9, 12], [13, 15, 16]] +""" + +from checker import print_matrix + + +def minor(matrix, i, j): + """ + This function calculates the minor matrix of a given matrix at the given + indices. + + Parameters + ---------- + matrix : list of lists + The input matrix. + i : int + The row index. + j : int + The column index. + + Returns + ------- + list of lists + The minor matrix of the given matrix at the given indices. + """ + return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])] + + +def main(): + matrix = [[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12], [13, 14, 15, 16]] + i = 1 + j = 1 + print_matrix(minor(matrix, i-1, j-1)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/multiplication.py b/Matrix Operations/multiplication.py new file mode 100644 index 00000000..f7d5a85a --- /dev/null +++ b/Matrix Operations/multiplication.py @@ -0,0 +1,106 @@ +""" +This module contains two functions to multiply matrices. + +The first function, `matrix_multiplication`, multiplies two matrices. The +function takes two matrices as arguments and returns the product of the two +matrices. The function first checks if the dimensions of the two matrices match. +If the dimensions do not match, the function raises a SystemExit exception. + +The function then creates a new matrix filled with zeros and calculates the +product of the two matrices by iterating over the elements of the matrices and +multiplying the corresponding elements together. The function then returns the +product of the two matrices. + +The second function, `scalar_matrix_multiplication`, multiplies a matrix by a +scalar. The function takes a scalar and a matrix as arguments and returns the +product of the scalar and the matrix. The function first checks if the matrix is +valid. If the matrix is not valid, the function raises a SystemExit exception. + +The function then multiplies each element of the matrix by the scalar and +returns the product of the scalar and the matrix. + +The module also contains a main function which tests the matrix multiplication +functions. + +Example: + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + matrix_multiplication(m1, m2) + [[30, 36, 42], [66, 81, 96], [102, 126, 150]] + + scalar_matrix_multiplication(5, m1) + [[5, 10, 15], [20, 25, 30], [35, 40, 45]] + +""" + +from checker import check_matrix_multiplication, validate_matrix, print_matrix +import sys + + +def matrix_multiplication(m1, m2): + """ + This function multiplies two matrices. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + list of lists: The product of the two matrices. + + Raises: + sys.exit: If the dimensions of the two matrices do not match. + """ + if check_matrix_multiplication(m1, m2) == False: + sys.exit("Matrix dimensions do not match") + + n = len(m1) + m = len(m1[0]) + l = len(m2[0]) + answer = [[0 for i in range(l)] for j in range(n)] + for i in range(n): + for j in range(m): + for k in range(l): + answer[i][j] += m1[i][k] * m2[k][j] + + return answer + + + +def scalar_matrix_multiplication(s, m): + """ + This function multiplies a matrix by a scalar. + + Args: + s (int): The scalar. + m (list of lists): The matrix. + + Returns: + list of lists: The product of the scalar and the matrix. + + Raises: + sys.exit: If the matrix is not valid. + """ + if validate_matrix(m) == False: + sys.exit("The 2D array is not a valid matrix") + for i in range(len(m)): + for j in range(len(m[0])): + m[i][j] = s * m[i][j] + return m + + + +def main(): + """ + This function tests the matrix multiplication functions. + + """ + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print_matrix(matrix_multiplication(m1, m2)) + print_matrix(scalar_matrix_multiplication(5, m1)) + + +if __name__ == "__main__": + main() + diff --git a/Matrix Operations/readme.md b/Matrix Operations/readme.md new file mode 100644 index 00000000..c7e5fea5 --- /dev/null +++ b/Matrix Operations/readme.md @@ -0,0 +1,113 @@ +# Matrix Operations Library +===================================== + +A collection of Python functions for performing various matrix operations. + +## Functions +------------- + +### 1. Checker +--------------- + +* **File:** `checker.py` +* **Description:** This program contains functions to validate a matrix, check if two matrices can be added or multiplied, and check if a matrix is square. It also contains a function to print a matrix. + +### 2. Input +------------- + +* **File:** `input.py` +* **Description:** This program asks the user to input a matrix and prints it back to the user. + +### 3. Matrix +------------- + +* **File:** `matrix.py` +* **Description:** This module contains functions to perform various matrix operations, including addition, subtraction, multiplication, transpose, rotate, cofactor, determinant, adjoint, inverse, swap, and sum. + +### 4. Addition +-------------- + +* **File:** `addition.py` +* **Description:** This program implements matrix addition. + +### 5. Subtraction +---------------- + +* **File:** `subtraction.py` +* **Description:** This program implements matrix subtraction. + +### 6. Multiplication +------------------ + +* **File:** `multiplication.py` +* **Description:** This module contains two functions to multiply matrices. + +### 7. Transpose +-------------- + +* **File:** `transpose.py` +* **Description:** This module contains functions to transpose a matrix. + +### 8. Rotate +------------ + +* **File:** `rotate.py` +* **Description:** This program rotates a matrix by 90, 180 or 270 degrees. + +### 9. Cofactor +------------- + +* **File:** `cofactor.py` +* **Description:** This module contains functions to calculate the cofactor matrix of a given matrix. + +### 10. Determinant +---------------- + +* **File:** `determinant.py` +* **Description:** This module contains a function to calculate the determinant of a matrix. + +### 11. Adjoint +------------- + +* **File:** `adjoint.py` +* **Description:** This module contains a function to calculate the adjoint matrix of a given matrix. + +### 12. Inverse +------------- + +* **File:** `inverse.py` +* **Description:** The inverse of a matrix is a matrix that when multiplied with the original matrix gives the identity matrix. + +### 13. Swap +------------ + +* **File:** `swap.py` +* **Description:** This module contains functions to swap rows and columns of a matrix. + +### 14. Sum +------------ + +* **File:** `sum.py` +* **Description:** This module contains functions to calculate the sum of all elements in a matrix, the trace of a matrix and the sum of the elements in the secondary diagonal of a matrix. + + + +## Usage +----- + +To use the functions in this library, simply import the corresponding module and call the desired function. For example, to add two matrices, you would import the `matrix` module and call the `add_matrices` function. + +```python +import matrix + +matrix1 = [[1, 2], [3, 4]] +matrix2 = [[5, 6], [7, 8]] + +result = matrix.add_matrices(matrix1, matrix2) +print(result) +``` + +## Contributed By +-------------- + +SammyUrfen diff --git a/Matrix Operations/rotate.py b/Matrix Operations/rotate.py new file mode 100644 index 00000000..1844df55 --- /dev/null +++ b/Matrix Operations/rotate.py @@ -0,0 +1,59 @@ +""" +This program rotates a matrix by 90, 180 or 270 degrees. + +It includes a function to rotate a matrix, and a main function to test the +rotation function. + +Example: + m = [[2, 4, 6, 14], [8, 10, 12, 17], [14, 16, 18, 45]] + rotate(m, 90) + # Output: + # [[14, 17, 45, 18], [12, 10, 8, 6], [6, 4, 2, 14]] + +""" +from transpose import transpose +from checker import print_matrix +import sys + + +def rotate(m, deg = 90): + """ + Rotate a matrix. + + This function takes a matrix and a rotation degree (90, 180 or 270) as input and returns its rotated version. + + Parameters + ---------- + m : list of lists + The matrix to be rotated. + + Returns + ------- + list of lists + The rotated matrix. + + Raises + ------ + sys.exit + If the matrix is not square. + """ + + if (deg!= 90 and deg!= 180 and deg!= 270): + sys.exit("Rotation degree must be 90, 180 or 270") + n = deg//90 + k = len(m) + for _ in range(n): + m = transpose(m) + for i in range(len(m)): + for j in range(len(m[i])//2): + m[i][j], m[i][k-j-1] = m[i][k-j-1], m[i][j] + return m + + +def main(): + m = [[2, 4, 6, 14], [8, 10, 12, 17], [14, 16, 18, 45]] + print_matrix(rotate(m, 90)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/subtraction.py b/Matrix Operations/subtraction.py new file mode 100644 index 00000000..d841b7e2 --- /dev/null +++ b/Matrix Operations/subtraction.py @@ -0,0 +1,57 @@ +""" +This program implements matrix subtraction. + +It includes a function to check if the dimensions of two matrices match, +a function to subtract the second matrix from the first, and a main function +to test the matrix subtraction function. + +Example: + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + matrix_subtraction(m1, m2) + [[0, 0, 0], [0, 0, 0], [0, 0, 0]] +""" + +from checker import check_matrix_dimension, print_matrix +import sys + + +def matrix_subtraction(m1, m2): + """ + This function subtracts the second matrix from the first. + + Args: + m1 (list of lists): The first matrix. + m2 (list of lists): The second matrix. + + Returns: + list of lists: The difference of the two matrices. + + Raises: + sys.exit: If the dimensions of the two matrices do not match. + """ + if check_matrix_dimension(m1, m2) == False: + sys.exit("Matrix dimensions do not match") + + n = len(m1) + m = len(m1[0]) + answer = [[0 for i in range(m)] for j in range(n)] + for i in range(len(m1)): + for j in range(len(m1[i])): + answer[i][j] = m1[i][j] - m2[i][j] + return answer + + +def main(): + """ + This function tests the matrix subtraction function. + + """ + m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print_matrix(matrix_subtraction(m1, m2)) + + +if __name__ == "__main__": + main() + diff --git a/Matrix Operations/sum.py b/Matrix Operations/sum.py new file mode 100644 index 00000000..effb7c26 --- /dev/null +++ b/Matrix Operations/sum.py @@ -0,0 +1,105 @@ +""" +This module contains functions to calculate the sum of all elements in a matrix, +the trace of a matrix and the sum of the elements in the secondary diagonal of a +matrix. + +The module contains the following functions: + +- `matrix_sum(m)`: This function takes a matrix as input and returns the sum of + all its elements. +- `trace(m)`: This function takes a matrix as input and returns the sum of the + elements in its main diagonal. +- `sum_secondary_diagonal(m)`: This function takes a matrix as input and + returns the sum of the elements in its secondary diagonal. + +The module also contains a main function which tests the above functions. + +Example: + m1 = [[1, 2, 10], [4, 5, 11], [7, 8, 12]] + matrix_sum(m1) + # Output: 45 + trace(m1) + # Output: 36 + sum_secondary_diagonal(m1) + # Output: 39 + +""" +from checker import validate_matrix, check_matrix_square +import sys + + +def matrix_sum(m): + """ + This function calculates the sum of all elements in a matrix. + + Args: + m (list of lists): The matrix whose sum is to be calculated. + + Returns: + int: The sum of all elements in the matrix. + + Raises: + sys.exit: If the 2D array is not a valid matrix. + """ + if not validate_matrix(m): + sys.exit("The 2D array is not a valid matrix") + sum = 0 + for i in range(len(m)): + for j in range(len(m[i])): + sum += m[i][j] + return sum + + +def trace(m): + """ + This function calculates the trace of a matrix. + + Args: + m (list of lists): The matrix whose trace is to be calculated. + + Returns: + int: The trace of the matrix. + + Raises: + sys.exit: If the matrix is not square. + """ + if not check_matrix_square(m): + sys.exit("The matrix is not square") + sum = 0 + for i in range(len(m)): + sum += m[i][i] + return sum + + +def sum_secondary_diagonal(m): + """ + This function calculates the sum of the elements in the secondary diagonal of + a matrix. + + Args: + m (list of lists): The matrix whose secondary diagonal sum is to be + calculated. + + Returns: + int: The sum of the elements in the secondary diagonal of the matrix. + + Raises: + sys.exit: If the matrix is not square. + """ + if not check_matrix_square(m): + sys.exit("The matrix is not square") + sum = 0 + for i in range(len(m)): + sum += m[i][len(m)-i-1] + return sum + + +def main(): + m1 = [[1, 2, 10], [4, 5, 11], [7, 8, 12]] + print(matrix_sum(m1)) + print(trace(m1)) + print(sum_secondary_diagonal(m1)) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/swap.py b/Matrix Operations/swap.py new file mode 100644 index 00000000..f1539b71 --- /dev/null +++ b/Matrix Operations/swap.py @@ -0,0 +1,68 @@ +""" +This module contains functions to swap rows and columns of a matrix. + +The module contains the following functions: + +- `swap_row(matrix, i, j)`: This function swaps the i-th and j-th rows of the + given matrix. +- `swap_column(matrix, i, j)`: This function swaps the i-th and j-th columns of + the given matrix. +- `main()`: This function is the main function of the program. It swaps rows and + columns of a matrix and prints the result. + +Example: + $ python swap.py + [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + [[4, 5, 6], [1, 2, 3], [7, 8, 9]] + [[3, 2, 1], [6, 5, 4], [9, 8, 7]] +""" + +from checker import validate_matrix, print_matrix +import sys + + +def swap_row(m, i, j): + """ + This function swaps the i-th and j-th rows of the given matrix. + + Args: + m (list of lists): The matrix to be modified. + i (int): The index of the first row to be swapped. + j (int): The index of the second row to be swapped. + """ + temp = m[i] + m[i] = m[j] + m[j] = temp + return + + +def swap_column(m, i, j): + """ + This function swaps the i-th and j-th columns of the given matrix. + + Args: + m (list of lists): The matrix to be modified. + i (int): The index of the first column to be swapped. + j (int): The index of the second column to be swapped. + """ + for lis in m: + lis[i], lis[j] = lis[j], lis[i] + return + + +def main(): + """ + This function is the main function of the program. It swaps rows and columns + of a matrix and prints the result. + """ + m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + print_matrix(m) + swap_row(m, 0, 1) + print_matrix(m) + m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + swap_column(m, 0, 2) + print_matrix(m) + + +if __name__ == "__main__": + main() diff --git a/Matrix Operations/transpose.py b/Matrix Operations/transpose.py new file mode 100644 index 00000000..bd4fb74b --- /dev/null +++ b/Matrix Operations/transpose.py @@ -0,0 +1,62 @@ +""" +This module contains functions to transpose a matrix. + +The module contains the following functions: + +- `transpose(matrix)`: This function takes a matrix as input and returns its + transpose. + +The module also contains a main function which tests the transpose function. + +Example: + m = [[2, 4, 6, 14], [8, 10, 12, 17], [14, 16, 18, 45]] + transpose(m) + # Output: + # [[2, 8, 14], [4, 10, 16], [6, 12, 18], [14, 17, 45]] +""" + +from checker import validate_matrix, print_matrix +import sys + + +def transpose(m): + """ + Transpose a matrix. + + Parameters + ---------- + m : list of lists + The matrix to be transposed. + + Returns + ------- + list of lists + The transposed matrix. + + Raises + ------ + sys.exit + If the matrix is not square. + """ + if validate_matrix(m) == False: + sys.exit("Matrix is not valid") + a = len(m) + b = len(m[0]) + answer = [[0 for i in range(a)] for j in range(b)] + for i in range(b): + for j in range(a): + answer[i][j] = m[j][i] + return answer + + +def main(): + """ + This function reads a matrix from the user and prints its transpose. + """ + m = [[2, 4, 6, 14], [8, 10, 12, 17], [14, 16, 18, 45]] + print_matrix(transpose(m)) + + +if __name__ == "__main__": + main() + diff --git a/README.md b/README.md index 97710f02..3fa0ffee 100644 --- a/README.md +++ b/README.md @@ -81,8 +81,9 @@ More information on contributing and the general code of conduct for discussion | JSON to YAML converter | [JSON to YAML converter](https://github.com/DhanushNehru/Python-Scripts/tree/master/JSON%20to%20YAML) | Converts JSON file to YAML files. A sample JSON is included for testing. | | Keylogger | [Keylogger](https://github.com/DhanushNehru/Python-Scripts/tree/master/Keylogger) | Keylogger that can track your keystrokes, clipboard text, take screenshots at regular intervals, and records audio. | | Keyword - Retweeting | [Keyword - Retweeting](https://github.com/DhanushNehru/Python-Scripts/tree/master/Keyword%20Retweet%20Twitter%20Bot) | Find the latest tweets containing given keywords and then retweet them. | -| LinkedIn Bot | [LinkedIn Bot](https://github.com/DhanushNehru/Python-Scripts/tree/master/LinkedIn%20Bot) | Automates the process of searching for public profiles on LinkedIn and exporting the data to an Excel sheet. | -| Mail Sender | [Mail Sender](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mail%20Sender) | Sends an email. | +| LinkedIn Bot | [LinkedIn Bot](https://github.com/DhanushNehru/Python-Scripts/tree/master/LinkedIn%20Bot) | Automates the process of searching for public profiles on LinkedIn and exporting the data to an Excel sheet. \ +| Mail Sender | [Mail Sender](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mail%20Sender) | Sends an email. | +| Matrix Operations | [Matrix Operations](https://github.com/SammyUrfen/Python-Scripts/tree/master/Matrix%20Operations) | Scripts for doing different operations and transformations to a Matrix. | Merge Two Images | [Merge Two Images](https://github.com/DhanushNehru/Python-Scripts/tree/master/Merge%20Two%20Images) | Merges two images horizontally or vertically. | | Mouse mover | [Mouse mover](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mouse%20Mover) | Moves your mouse every 15 seconds. | | No Screensaver | [No Screensaver](https://github.com/DhanushNehru/Python-Scripts/tree/master/No%20Screensaver) | Prevents screensaver from turning on. | diff --git a/Sorting/bubblesort-explanation.py b/Sorting/bubblesort-explanation.py new file mode 100644 index 00000000..0be6cac0 --- /dev/null +++ b/Sorting/bubblesort-explanation.py @@ -0,0 +1,38 @@ +def bubble_sort_with_explanation(arr): + n = len(arr) + + print(f"Initial array: {arr}") + print("\nStarting Bubble Sort...") + + for i in range(n): + print(f"\nPass {i + 1}:") + + # Flag to check if any swap happened in this pass + swapped = False + + for j in range(0, n - i - 1): + print(f" Comparing {arr[j]} and {arr[j + 1]}") + + if arr[j] > arr[j + 1]: + print(f" Swapping {arr[j]} and {arr[j + 1]} since {arr[j]} > {arr[j + 1]}") + arr[j], arr[j + 1] = arr[j + 1], arr[j] + swapped = True + else: + print(" No swap needed") + + print(f" Array after comparison: {arr}") + + print(f"Array after pass {i + 1}: {arr}") + + # If no swapping occurred, array is already sorted + if not swapped: + print(f"\nArray is already sorted after pass {i + 1}. Stopping early.") + break + + print("\nSorting completed!") + print(f"Final sorted array: {arr}") + +# Test the function +if __name__ == "__main__": + test_array = [64, 34, 25, 12, 22, 11, 90] + bubble_sort_with_explanation(test_array) \ No newline at end of file diff --git a/Sorting/insertionsort-explanation.py b/Sorting/insertionsort-explanation.py new file mode 100644 index 00000000..39330100 --- /dev/null +++ b/Sorting/insertionsort-explanation.py @@ -0,0 +1,51 @@ +""" +This program implements the insertion sort algorithm and prints out each step of the process. + +The function insertion_sort_with_explanation takes in an array and sorts it using the insertion sort algorithm. It prints out the state of the array at each step of the process, explaining what's happening. +""" + +def insertion_sort_with_explanation(arr): + """ + Sorts the given array using insertion sort and prints out each step of the process. + + :param arr: The array to be sorted + :type arr: list + :return: The sorted array + :rtype: list + """ + print("Initial array:", arr) + print("\nBeginning Insertion Sort:\n") + + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + print(f"Step {i}:") + print(f" Current element to insert: {key}") + print(f" Current array state: {arr}") + + if arr[j] <= key: + print(f" {key} is already in the correct position.") + else: + print(f" Finding the correct position for {key}:") + + while j >= 0 and arr[j] > key: + print(f" Comparing {key} with {arr[j]}") + print(f" {arr[j]} > {key}, so moving {arr[j]} to the right") + arr[j + 1] = arr[j] + j -= 1 + print(f" Current array state: {arr}") + + if j + 1 != i: + arr[j + 1] = key + print(f" Inserted {key} at index {j + 1}") + print(f" Array after insertion: {arr}") + + print() # Empty line for readability + + print("Sorting complete. Final array:", arr) + + +# Test the function +if __name__ == "__main__": + test_array = [64, 34, 25, 12, 22, 11, 90] + insertion_sort_with_explanation(test_array) diff --git a/Sorting/readme.md b/Sorting/readme.md new file mode 100644 index 00000000..e3e56683 --- /dev/null +++ b/Sorting/readme.md @@ -0,0 +1,34 @@ +# Sorting Algorithms +====================== + +This folder contains implementations of three common sorting algorithms in Python: Insertion Sort, Bubble Sort, and Selection Sort. Additionally, there are explanation scripts that print out the steps involved in each sorting process. + +## Algorithms +------------ + +### Insertion Sort + +* Implementation: `insertionsort.py` +* Explanation: `insertionsort-explanation.py` + +### Bubble Sort + +* Implementation: `bubblesort.py` +* Explanation: `bubblesort-explanation.py` + +### Selection Sort + +* Implementation: `selectionsort.py` +* Explanation: `selectionsort-explanation.py` + +## Usage +----- + +To run the implementations, simply execute the corresponding Python script. For example, to run the Insertion Sort implementation, run `python insertionsort.py`. + +To see the step-by-step explanation of each sorting process, run the corresponding explanation script. For example, to see the explanation of Insertion Sort, run `python insertionsort-explanation.py`. + +## Contributing +------------ + +Feel free to contribute to this repository by adding more sorting algorithms or improving the existing implementations. \ No newline at end of file diff --git a/Sorting/selectionsort-explanation.py b/Sorting/selectionsort-explanation.py new file mode 100644 index 00000000..974d7b63 --- /dev/null +++ b/Sorting/selectionsort-explanation.py @@ -0,0 +1,43 @@ +def selection_sort_with_explaination(arr): + """ + Sorts the given array using selection sort and prints out each step of the process. + + :param arr: The array to be sorted + :type arr: list + :return: The sorted array + :rtype: list + """ + n = len(arr) + + print(f"Initial array: {arr}") + print("\nStarting Selection Sort...") + + for i in range(n): + print(f"\nIteration {i + 1}:") + print(f"Current array: {arr}") + + # Find the minimum element in the unsorted part of the array + min_idx = i + print(f"Looking for the minimum element starting from index {i}") + + for j in range(i + 1, n): + if arr[j] < arr[min_idx]: + min_idx = j + print(f" New minimum found: {arr[min_idx]} at index {min_idx}") + + # Swap the found minimum element with the first element of the unsorted part + if min_idx != i: + print(f"Swapping {arr[i]} at index {i} with {arr[min_idx]} at index {min_idx}") + arr[i], arr[min_idx] = arr[min_idx], arr[i] + else: + print(f"No swap needed. {arr[i]} at index {i} is already in the correct position.") + + print(f"Array after iteration {i + 1}: {arr}") + + print("\nSorting completed!") + print(f"Final sorted array: {arr}") + +# Test the function +if __name__ == "__main__": + test_array = [64, 34, 25, 12, 22, 11, 90] + selection_sort_with_explaination(test_array) diff --git a/Star Pattern/README.md b/Star Pattern/README.md index 97a603d1..b2050698 100644 --- a/Star Pattern/README.md +++ b/Star Pattern/README.md @@ -4,13 +4,55 @@ You can contribute by adding more python scripts which can be used to automate t Incase you have anything to be followed while executing the python script mention it as well -# Python Script +# Star Pattern +================ -## Script - Star Pattern +This folder contains Python scripts to create various patterns with '*' (stars). -Code to create star pattern -starPattern.py +## Scripts +-------- +### 1. starPattern.py +Creates a star pattern pyramid. + +### 2. inversestarPattern.py + +Creates an inverse star pattern pyramid. + +### 3. rightstarPattern.py + +Creates a right-aligned star pattern pyramid. + +### 4. rightinversestarPattern.py + +Creates a right-aligned inverse star pattern pyramid. + +### 5. pyramid.py + +Creates a pyramid pattern. + +### 6. inversePyramid.py + +Creates an inverse pyramid pattern. + +### 7. diamond.py + +Creates a diamond pattern. + +### 8. reverseDiamond.py + +Creates a reverse diamond pattern. + +### 9. Star.py + +Creates a star pattern. + +## Contributed By +-------------- + +Daksh Jain, +marialee222, +SammyUrfen \ No newline at end of file diff --git a/Star Pattern/Star.py b/Star Pattern/Star.py new file mode 100644 index 00000000..5a2bc549 --- /dev/null +++ b/Star Pattern/Star.py @@ -0,0 +1,48 @@ +def Star(n): + # Upper part of the star + for i in range(1, n + 1): + for j in range(n): + print(" ", end="") + for j in range(1, n - i + 1): + print(" ", end="") + for j in range(1, 2 * i): + print("* ", end="") + print() + + # Upper middle part of the star + for i in range(1, n + 1): + for j in range(n - 1, n - i, -1): + print(" ", end="") + for j in range(1, n - i + 2): + print("* ", end="") + for j in range(1, 2 * n): + print("* ", end="") + for j in range(1, n - i + 2): + print("* ", end="") + print() + + # Lower middle part of the star + for i in range(1, n + 1): + for j in range(1, n - i + 1): + print(" ", end="") + for j in range(1, i + 1): + print("* ", end="") + for j in range(1, 2 * n): + print("* ", end="") + for j in range(1, i + 1): + print("* ", end="") + print() + + # Lower part of the star + for i in range(n, 0, -1): + for j in range(n): + print(" ", end="") + for j in range(1, n - i + 1): + print(" ", end="") + for j in range(1, 2 * i): + print("* ", end="") + print() + +if __name__ == "__main__": + n = int(input("Enter the size of the star: ")) + Star(n) \ No newline at end of file diff --git a/Star Pattern/diamond.py b/Star Pattern/diamond.py new file mode 100644 index 00000000..8b7a90f7 --- /dev/null +++ b/Star Pattern/diamond.py @@ -0,0 +1,18 @@ +def diamond(n): + for i in range(n): + for j in range(n-i): + print(" ", end="") + for k in range(i+1): + print("* ", end="") + print() + for i in range(n-2, -1, -1): + for j in range(n-i): + print(" ", end="") + for k in range(i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height of half the diamond : ")) + diamond(n) \ No newline at end of file diff --git a/Star Pattern/inversePyramid.py b/Star Pattern/inversePyramid.py new file mode 100644 index 00000000..aab8169d --- /dev/null +++ b/Star Pattern/inversePyramid.py @@ -0,0 +1,12 @@ +def inversePyramid(n): + for i in range(n, -1, -1): + for j in range(n-i): + print(" ", end="") + for k in range(i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + inversePyramid(n) \ No newline at end of file diff --git a/Star Pattern/inversestarPattern.py b/Star Pattern/inversestarPattern.py new file mode 100644 index 00000000..8e8654dc --- /dev/null +++ b/Star Pattern/inversestarPattern.py @@ -0,0 +1,10 @@ +def inversestarPattern(n): + for i in range(n+1, 0, -1): + for j in range(1, i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + inversestarPattern(n) \ No newline at end of file diff --git a/Star Pattern/pyramid.py b/Star Pattern/pyramid.py new file mode 100644 index 00000000..240c03a7 --- /dev/null +++ b/Star Pattern/pyramid.py @@ -0,0 +1,12 @@ +def pyramid(n): + for i in range(n): + for j in range(n-i): + print(" ", end="") + for k in range(i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + pyramid(n) \ No newline at end of file diff --git a/Star Pattern/reverseDiamond.py b/Star Pattern/reverseDiamond.py new file mode 100644 index 00000000..6b29663f --- /dev/null +++ b/Star Pattern/reverseDiamond.py @@ -0,0 +1,22 @@ +def reverseDiamond(n): + for i in range(1, n + 1): + for j in range(1, 2 * n): + if n - i + 1 < j < n + i - 1: + print(" ", end="") + else: + print("*", end="") + print() + + for i in range(n-1, 0, -1): + for j in range(1, 2 * n): + if n - i + 1 < j < n + i - 1: + print(" ", end="") + else: + print("*", end="") + print() + + + +if __name__ == "__main__": + n = int(input("Enter the height of half the diamond : ")) + reverseDiamond(n) \ No newline at end of file diff --git a/Star Pattern/rightiversestarPattern.py b/Star Pattern/rightiversestarPattern.py new file mode 100644 index 00000000..3cf1cf29 --- /dev/null +++ b/Star Pattern/rightiversestarPattern.py @@ -0,0 +1,12 @@ +def rightinversestarPattern(n): + for i in range(n+1, 0, -1): + for j in range(n-i+1, 0, -1): + print(" ", end="") + for j in range(1, i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + rightinversestarPattern(n) \ No newline at end of file diff --git a/Star Pattern/rightstarPattern.py b/Star Pattern/rightstarPattern.py new file mode 100644 index 00000000..d1a20a99 --- /dev/null +++ b/Star Pattern/rightstarPattern.py @@ -0,0 +1,12 @@ +def rightstarPattern(n): + for i in range(1, n+1): + for j in range(1, n-i+1): + print(" ", end="") + for j in range(1, i+1): + print("* ", end="") + print() + + +if __name__ == "__main__": + n = int(input("Enter the height : ")) + rightstarPattern(n) \ No newline at end of file diff --git a/Star Pattern/starPattern.py b/Star Pattern/starPattern.py index 9b9dc3c5..886bc8e3 100644 --- a/Star Pattern/starPattern.py +++ b/Star Pattern/starPattern.py @@ -5,6 +5,7 @@ def starPattern(n): print() -n = int(input("Enter the number of rows: ")) -starPattern(n) +if __name__ == "__main__": + n = int(input("Enter the height : ")) + starPattern(n)