Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Mathematical & Statistical Snippets Issue #17 #18 #19

Merged
merged 4 commits into from
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,6 @@ cython_debug/
# pypi
build/
dist/
pysnippets.egg-info/
pysnippets.egg-info/

.vscode/
22 changes: 22 additions & 0 deletions Tests/data_distribution.py
Original file line number Diff line number Diff line change
@@ -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()
24 changes: 24 additions & 0 deletions Tests/matrix_operations.py
Original file line number Diff line number Diff line change
@@ -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()
34 changes: 34 additions & 0 deletions Tests/statistics.py
Original file line number Diff line number Diff line change
@@ -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()
20 changes: 20 additions & 0 deletions Tests/test_complex_number.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 1 addition & 1 deletion Tests/test_file_organizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand Down
2 changes: 1 addition & 1 deletion Tests/test_number_formatting.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
73 changes: 73 additions & 0 deletions pysnippets/Mathematics/complex_number_operations.py
Original file line number Diff line number Diff line change
@@ -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)
45 changes: 45 additions & 0 deletions pysnippets/Mathematics/determinant.py
Original file line number Diff line number Diff line change
@@ -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)
44 changes: 44 additions & 0 deletions pysnippets/Mathematics/matrix_multiplication.py
Original file line number Diff line number Diff line change
@@ -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)
53 changes: 53 additions & 0 deletions pysnippets/Mathematics/polar_rectangular_conversion.py
Original file line number Diff line number Diff line change
@@ -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)
Loading