From 640eeaa648e5a3d5f36f01c09b94f1ce7604f667 Mon Sep 17 00:00:00 2001 From: SpreadSheets600 Date: Sat, 5 Oct 2024 18:40:21 +0530 Subject: [PATCH 1/4] Added Mathematical Snippets #17 --- Tests/matrix_operations.py | 24 ++++++ Tests/test_complex_number.py | 20 +++++ .../Mathematics/complex_number_operations.py | 73 +++++++++++++++++++ pysnippets/Mathematics/determinant.py | 45 ++++++++++++ .../Mathematics/matrix_multiplication.py | 44 +++++++++++ .../polar_rectangular_conversion.py | 53 ++++++++++++++ 6 files changed, 259 insertions(+) create mode 100644 Tests/matrix_operations.py create mode 100644 Tests/test_complex_number.py create mode 100644 pysnippets/Mathematics/complex_number_operations.py create mode 100644 pysnippets/Mathematics/determinant.py create mode 100644 pysnippets/Mathematics/matrix_multiplication.py create mode 100644 pysnippets/Mathematics/polar_rectangular_conversion.py diff --git a/Tests/matrix_operations.py b/Tests/matrix_operations.py new file mode 100644 index 0000000..d0eab88 --- /dev/null +++ b/Tests/matrix_operations.py @@ -0,0 +1,24 @@ +import unittest +from snippets.matrix_operations import add_matrices, multiply_matrices, transpose_matrix + +class TestMatrixOperations(unittest.TestCase): + + def test_add_matrices(self): + # Test case for normal behavior + self.assertEqual(add_matrices([[1, 2], [3, 4]], [[5, 6], [7, 8]]), [[6, 8], [10, 12]]) + + def test_multiply_matrices(self): + # Test case for normal behavior + self.assertEqual(multiply_matrices([[1, 2], [3, 4]], [[5, 6], [7, 8]]), [[19, 22], [43, 50]]) + + def test_transpose_matrix(self): + # Test case for normal behavior + self.assertEqual(transpose_matrix([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]]) + + def test_add_matrices_invalid(self): + # Test case for invalid input + with self.assertRaises(ValueError): + add_matrices([[1, 2]], [[3, 4], [5, 6]]) + +if __name__ == '__main__': + unittest.main() diff --git a/Tests/test_complex_number.py b/Tests/test_complex_number.py new file mode 100644 index 0000000..929af39 --- /dev/null +++ b/Tests/test_complex_number.py @@ -0,0 +1,20 @@ +import unittest +from snippets.complex_numbers import add_complex, multiply_complex + +class TestComplexNumbers(unittest.TestCase): + + def test_add_complex(self): + # Test case for normal behavior + self.assertEqual(add_complex((1, 2), (3, 4)), (4, 6)) + + def test_multiply_complex(self): + # Test case for normal behavior + self.assertEqual(multiply_complex((1, 2), (3, 4)), (-5, 10)) + + def test_add_complex_invalid(self): + # Test case for invalid input + with self.assertRaises(TypeError): + add_complex((1, 2), "string") + +if __name__ == '__main__': + unittest.main() diff --git a/pysnippets/Mathematics/complex_number_operations.py b/pysnippets/Mathematics/complex_number_operations.py new file mode 100644 index 0000000..e2ca7dc --- /dev/null +++ b/pysnippets/Mathematics/complex_number_operations.py @@ -0,0 +1,73 @@ +# complex_number_operations.py + +def add_complex(c1, c2): + """ + Add two complex numbers. + + Args: + c1 (tuple): The first complex number as (real, imag). + c2 (tuple): The second complex number as (real, imag). + + Returns: + tuple: The sum of the two complex numbers as (real, imag). + + Example: + >>> add_complex((1, 2), (3, 4)) + (4, 6) + """ + real = c1[0] + c2[0] + imag = c1[1] + c2[1] + return (real, imag) + +def subtract_complex(c1, c2): + """ + Subtract the second complex number from the first. + + Args: + c1 (tuple): The first complex number as (real, imag). + c2 (tuple): The second complex number as (real, imag). + + Returns: + tuple: The difference of the two complex numbers as (real, imag). + + Example: + >>> subtract_complex((5, 7), (2, 3)) + (3, 4) + """ + real = c1[0] - c2[0] + imag = c1[1] - c2[1] + return (real, imag) + +def multiply_complex(c1, c2): + """ + Multiply two complex numbers. + + Args: + c1 (tuple): The first complex number as (real, imag). + c2 (tuple): The second complex number as (real, imag). + + Returns: + tuple: The product of the two complex numbers as (real, imag). + + Example: + >>> multiply_complex((1, 2), (3, 4)) + (-5, 10) + """ + real = c1[0] * c2[0] - c1[1] * c2[1] + imag = c1[0] * c2[1] + c1[1] * c2[0] + return (real, imag) + +# Example usage +if __name__ == "__main__": + # Example usage of the functions + c1 = (1, 2) # 1 + 2i + c2 = (3, 4) # 3 + 4i + + sum_result = add_complex(c1, c2) + print("Sum:", sum_result) + + difference_result = subtract_complex(c1, c2) + print("Difference:", difference_result) + + product_result = multiply_complex(c1, c2) + print("Product:", product_result) diff --git a/pysnippets/Mathematics/determinant.py b/pysnippets/Mathematics/determinant.py new file mode 100644 index 0000000..bc95afe --- /dev/null +++ b/pysnippets/Mathematics/determinant.py @@ -0,0 +1,45 @@ +# determinant_calculation.py + +def determinant(matrix): + """ + Compute the determinant of a square matrix. + + Args: + matrix (list of list of int/float): The square matrix for which the determinant is to be calculated. + + Returns: + int/float: The determinant of the matrix. + + Raises: + ValueError: If the matrix is not square (number of rows must equal number of columns). + + Example: + >>> matrix = [[1, 2, 3], [0, 1, 4], [5, 6, 0]] + >>> determinant(matrix) + -34 + """ + # Check if the matrix is square + n = len(matrix) + if any(len(row) != n for row in matrix): + raise ValueError("Matrix must be square (same number of rows and columns).") + + # Base case for 2x2 matrix + if n == 2: + return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] + + # Recursive case for larger matrices + det = 0 + for c in range(n): + # Calculate the minor matrix + minor = [row[:c] + row[c+1:] for row in matrix[1:]] + # Recursive call to determinant for the minor + det += ((-1) ** c) * matrix[0][c] * determinant(minor) + + return det + +# Example usage +if __name__ == "__main__": + # Example usage of the function + matrix = [[1, 2, 3], [0, 1, 4], [5, 6, 0]] + result = determinant(matrix) + print(result) diff --git a/pysnippets/Mathematics/matrix_multiplication.py b/pysnippets/Mathematics/matrix_multiplication.py new file mode 100644 index 0000000..54e4573 --- /dev/null +++ b/pysnippets/Mathematics/matrix_multiplication.py @@ -0,0 +1,44 @@ +# matrix_multiplication.py + +def matrix_multiply(A, B): + """ + Multiply two matrices A and B. + + Args: + A (list of list of int/float): First matrix. + B (list of list of int/float): Second matrix. + + Returns: + list of list of int/float: The resulting matrix after multiplication. + + Raises: + ValueError: If the number of columns in A does not match the number of rows in B. + + Example: + >>> A = [[1, 2, 3], [4, 5, 6]] + >>> B = [[7, 8], [9, 10], [11, 12]] + >>> matrix_multiply(A, B) + [[58, 64], [139, 154]] + """ + # Check if the number of columns in A matches the number of rows in B + if len(A[0]) != len(B): + raise ValueError("Number of columns in A must match number of rows in B.") + + # Initialize the result matrix with zeros + result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))] + + # Perform matrix multiplication + for i in range(len(A)): + for j in range(len(B[0])): + for k in range(len(B)): + result[i][j] += A[i][k] * B[k][j] + + return result + +# Example usage +if __name__ == "__main__": + # Example usage of the function + A = [[1, 2, 3], [4, 5, 6]] + B = [[7, 8], [9, 10], [11, 12]] + result = matrix_multiply(A, B) + print(result) diff --git a/pysnippets/Mathematics/polar_rectangular_conversion.py b/pysnippets/Mathematics/polar_rectangular_conversion.py new file mode 100644 index 0000000..451d7f0 --- /dev/null +++ b/pysnippets/Mathematics/polar_rectangular_conversion.py @@ -0,0 +1,53 @@ +# polar_rectangular_conversion.py + +import math + +def polar_to_rectangular(r, theta): + """ + Convert polar coordinates to rectangular coordinates. + + Args: + r (float): The radial distance from the origin. + theta (float): The angle in radians. + + Returns: + tuple: The rectangular coordinates as (x, y). + + Example: + >>> polar_to_rectangular(5, math.pi / 4) + (3.5355339059327378, 3.5355339059327373) + """ + x = r * math.cos(theta) + y = r * math.sin(theta) + return (x, y) + +def rectangular_to_polar(x, y): + """ + Convert rectangular coordinates to polar coordinates. + + Args: + x (float): The x-coordinate. + y (float): The y-coordinate. + + Returns: + tuple: The polar coordinates as (r, theta). + + Example: + >>> rectangular_to_polar(3, 4) + (5.0, 0.9272952180016122) + """ + r = math.sqrt(x ** 2 + y ** 2) + theta = math.atan2(y, x) + return (r, theta) + +# Example usage +if __name__ == "__main__": + # Example usage of the functions + r = 5 + theta = math.pi / 4 + rectangular = polar_to_rectangular(r, theta) + print("Rectangular Coordinates:", rectangular) + + x, y = 3, 4 + polar = rectangular_to_polar(x, y) + print("Polar Coordinates:", polar) From 1a307ae98b8fb4840693b906f1f73aba53e6595e Mon Sep 17 00:00:00 2001 From: SpreadSheets600 Date: Sat, 5 Oct 2024 19:12:36 +0530 Subject: [PATCH 2/4] Added Statistics Snippets Issue #18 --- Tests/data_distribution.py | 22 +++++++ Tests/statistics.py | 34 +++++++++++ Tests/test_file_organizer.py | 2 +- Tests/test_number_formatting.py | 2 +- .../__init__.py | 0 .../file_organizer.py | 0 pysnippets/Statistics/mean_median_mode.py | 60 +++++++++++++++++++ pysnippets/Statistics/quantile.py | 24 ++++++++ pysnippets/Statistics/standard_deviation.py | 18 ++++++ pysnippets/Statistics/variance.py | 23 +++++++ .../Statistics/z_score_normalization.py | 21 +++++++ 11 files changed, 204 insertions(+), 2 deletions(-) create mode 100644 Tests/data_distribution.py create mode 100644 Tests/statistics.py rename pysnippets/{File_Organizer => FileOrganizer}/__init__.py (100%) rename pysnippets/{File_Organizer => FileOrganizer}/file_organizer.py (100%) create mode 100644 pysnippets/Statistics/mean_median_mode.py create mode 100644 pysnippets/Statistics/quantile.py create mode 100644 pysnippets/Statistics/standard_deviation.py create mode 100644 pysnippets/Statistics/variance.py create mode 100644 pysnippets/Statistics/z_score_normalization.py diff --git a/Tests/data_distribution.py b/Tests/data_distribution.py new file mode 100644 index 0000000..026c555 --- /dev/null +++ b/Tests/data_distribution.py @@ -0,0 +1,22 @@ +import unittest +from snippets.statistics import quantile, z_score_normalization + +class TestDataDistribution(unittest.TestCase): + + def test_quantile(self): + self.assertEqual(quantile([1, 2, 3, 4, 5], 0.5), 3) + self.assertEqual(quantile([1, 2, 3, 4, 5], 0.25), 2) + with self.assertRaises(ValueError): + quantile([], 0.5) + with self.assertRaises(ValueError): + quantile([1, 2, 3, 4, 5], 1.5) + + def test_z_score_normalization(self): + self.assertAlmostEqual(z_score_normalization([1, 2, 3, 4, 5]), + [-1.4142135623730951, -0.7071067811865475, 0.0, 0.7071067811865475, 1.4142135623730951], + places=6) + with self.assertRaises(ValueError): + z_score_normalization([]) + +if __name__ == '__main__': + unittest.main() diff --git a/Tests/statistics.py b/Tests/statistics.py new file mode 100644 index 0000000..89d822f --- /dev/null +++ b/Tests/statistics.py @@ -0,0 +1,34 @@ +import unittest +from snippets.statistics import mean, median, mode, variance, standard_deviation + +class TestStatistics(unittest.TestCase): + + def test_mean(self): + self.assertEqual(mean([1, 2, 3, 4]), 2.5) + with self.assertRaises(ValueError): + mean([]) + + def test_median(self): + self.assertEqual(median([1, 2, 3, 4, 5]), 3) + with self.assertRaises(ValueError): + median([]) + + def test_mode(self): + self.assertEqual(mode([1, 2, 2, 3, 4]), 2) + with self.assertRaises(ValueError): + mode([]) + + def test_variance(self): + self.assertEqual(variance([1, 2, 3, 4], population=True), 1.25) + self.assertEqual(variance([1, 2, 3, 4], population=False), 1.6666666666666667) + with self.assertRaises(ValueError): + variance([]) + + def test_standard_deviation(self): + self.assertEqual(standard_deviation([1, 2, 3, 4], population=True), 1.118033988749895) + self.assertEqual(standard_deviation([1, 2, 3, 4], population=False), 1.2909944487358056) + with self.assertRaises(ValueError): + standard_deviation([]) + +if __name__ == '__main__': + unittest.main() diff --git a/Tests/test_file_organizer.py b/Tests/test_file_organizer.py index 6e9db15..baa9791 100644 --- a/Tests/test_file_organizer.py +++ b/Tests/test_file_organizer.py @@ -4,7 +4,7 @@ import os import tempfile import shutil -from Snippets.File_Organizer.file_organizer import organize_files_by_type +from pysnippets.FileOrganizer.file_organizer import organize_files_by_type class TestOrganizeFilesByType(unittest.TestCase): diff --git a/Tests/test_number_formatting.py b/Tests/test_number_formatting.py index 2ba7c73..d7528a3 100644 --- a/Tests/test_number_formatting.py +++ b/Tests/test_number_formatting.py @@ -1,7 +1,7 @@ # test_number_formatting.py import unittest -from Snippets.Numbers.number_formatting import format_number +from pysnippets.Numbers.number_formatting import format_number class TestNumberFormatting(unittest.TestCase): diff --git a/pysnippets/File_Organizer/__init__.py b/pysnippets/FileOrganizer/__init__.py similarity index 100% rename from pysnippets/File_Organizer/__init__.py rename to pysnippets/FileOrganizer/__init__.py diff --git a/pysnippets/File_Organizer/file_organizer.py b/pysnippets/FileOrganizer/file_organizer.py similarity index 100% rename from pysnippets/File_Organizer/file_organizer.py rename to pysnippets/FileOrganizer/file_organizer.py diff --git a/pysnippets/Statistics/mean_median_mode.py b/pysnippets/Statistics/mean_median_mode.py new file mode 100644 index 0000000..1770d3d --- /dev/null +++ b/pysnippets/Statistics/mean_median_mode.py @@ -0,0 +1,60 @@ +# statistics.py + +def mean(data): + """ + Calculate the mean of a list of numbers. + + Args: + data (list): A list of numbers. + + Returns: + float: The mean of the numbers. + + Example: + >>> mean([1, 2, 3, 4]) + 2.5 + """ + if not data: + raise ValueError("List is empty") + return sum(data) / len(data) + +def median(data): + """ + Calculate the median of a list of numbers. + + Args: + data (list): A list of numbers. + + Returns: + float: The median of the numbers. + + Example: + >>> median([1, 2, 3, 4, 5]) + 3 + """ + if not data: + raise ValueError("List is empty") + sorted_data = sorted(data) + n = len(sorted_data) + mid = n // 2 + return (sorted_data[mid] + sorted_data[-mid - 1]) / 2 if n % 2 == 0 else sorted_data[mid] + +def mode(data): + """ + Calculate the mode of a list of numbers. + + Args: + data (list): A list of numbers. + + Returns: + int or float: The mode of the numbers. + + Example: + >>> mode([1, 2, 2, 3, 4]) + 2 + """ + if not data: + raise ValueError("List is empty") + from collections import Counter + count = Counter(data) + return count.most_common(1)[0][0] diff --git a/pysnippets/Statistics/quantile.py b/pysnippets/Statistics/quantile.py new file mode 100644 index 0000000..14a377e --- /dev/null +++ b/pysnippets/Statistics/quantile.py @@ -0,0 +1,24 @@ +# statistics.py (continued) + +def quantile(data, q): + """ + Calculate the q-th quantile of a list of numbers. + + Args: + data (list): A list of numbers. + q (float): The quantile to calculate (between 0 and 1). + + Returns: + float: The q-th quantile of the numbers. + + Example: + >>> quantile([1, 2, 3, 4, 5], 0.5) + 3 + """ + if not data: + raise ValueError("List is empty") + if not (0 <= q <= 1): + raise ValueError("Quantile must be between 0 and 1") + sorted_data = sorted(data) + index = int(q * (len(sorted_data) - 1)) + return sorted_data[index] diff --git a/pysnippets/Statistics/standard_deviation.py b/pysnippets/Statistics/standard_deviation.py new file mode 100644 index 0000000..e5761ec --- /dev/null +++ b/pysnippets/Statistics/standard_deviation.py @@ -0,0 +1,18 @@ +from variance import variance + +def standard_deviation(data, population=True): + """ + Calculate the standard deviation of a list of numbers. + + Args: + data (list): A list of numbers. + population (bool): If True, calculate population standard deviation; otherwise, sample. + + Returns: + float: The standard deviation of the numbers. + + Example: + >>> standard_deviation([1, 2, 3, 4], population=True) + 1.118033988749895 + """ + return variance(data, population) ** 0.5 diff --git a/pysnippets/Statistics/variance.py b/pysnippets/Statistics/variance.py new file mode 100644 index 0000000..6fe3d0f --- /dev/null +++ b/pysnippets/Statistics/variance.py @@ -0,0 +1,23 @@ +# statistics.py (continued) + +from mean_median_mode import mean + +def variance(data, population=True): + """ + Calculate the variance of a list of numbers. + + Args: + data (list): A list of numbers. + population (bool): If True, calculate population variance; otherwise, sample variance. + + Returns: + float: The variance of the numbers. + + Example: + >>> variance([1, 2, 3, 4], population=True) + 1.25 + """ + if not data: + raise ValueError("List is empty") + mean_value = mean(data) + return sum((x - mean_value) ** 2 for x in data) / (len(data) if population else len(data) - 1) diff --git a/pysnippets/Statistics/z_score_normalization.py b/pysnippets/Statistics/z_score_normalization.py new file mode 100644 index 0000000..50b4cbb --- /dev/null +++ b/pysnippets/Statistics/z_score_normalization.py @@ -0,0 +1,21 @@ +# statistics.py (continued) + +def z_score_normalization(data): + """ + Normalize a list of numbers using Z-score normalization. + + Args: + data (list): A list of numbers. + + Returns: + list: The normalized values. + + Example: + >>> z_score_normalization([1, 2, 3, 4, 5]) + [-1.4142135623730951, -0.7071067811865475, 0.0, 0.7071067811865475, 1.4142135623730951] + """ + if not data: + raise ValueError("List is empty") + mean_value = mean(data) + std_dev = standard_deviation(data) + return [(x - mean_value) / std_dev for x in data] From 25bfb45422de876bd16850b9fd14fdba081aea1e Mon Sep 17 00:00:00 2001 From: SpreadSheets600 Date: Sat, 5 Oct 2024 19:20:33 +0530 Subject: [PATCH 3/4] Bug Fixes #17 #18 --- .vscode/settings.json | 5 +++++ pysnippets/Statistics/z_score_normalization.py | 3 +++ 2 files changed, 8 insertions(+) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..a490b61 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "githubPullRequests.ignoredPullRequestBranches": [ + "main" + ] +} \ No newline at end of file diff --git a/pysnippets/Statistics/z_score_normalization.py b/pysnippets/Statistics/z_score_normalization.py index 50b4cbb..b4084c2 100644 --- a/pysnippets/Statistics/z_score_normalization.py +++ b/pysnippets/Statistics/z_score_normalization.py @@ -1,5 +1,8 @@ # statistics.py (continued) +from mean_median_mode import mean +from standard_deviation import standard_deviation + def z_score_normalization(data): """ Normalize a list of numbers using Z-score normalization. From eea1b2f8e44ed656138ccd76b822e80d7f12ea04 Mon Sep 17 00:00:00 2001 From: SpreadSheets600 Date: Sat, 5 Oct 2024 19:32:17 +0530 Subject: [PATCH 4/4] Ignored .vscode Folder --- .gitignore | 4 +++- .vscode/settings.json | 5 ----- 2 files changed, 3 insertions(+), 6 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.gitignore b/.gitignore index 3b40b53..5b91df4 100644 --- a/.gitignore +++ b/.gitignore @@ -164,4 +164,6 @@ cython_debug/ # pypi build/ dist/ -pysnippets.egg-info/ \ No newline at end of file +pysnippets.egg-info/ + +.vscode/ \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index a490b61..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "githubPullRequests.ignoredPullRequestBranches": [ - "main" - ] -} \ No newline at end of file