Skip to content

Commit 490e645

Browse files
CaedenPHgithub-actionstianyizheng02
authored
Fix minor typing errors in maths/ (TheAlgorithms#8959)
* updating DIRECTORY.md * types(maths): Fix pylance issues in maths * reset(vsc): Reset settings changes * Update maths/jaccard_similarity.py Co-authored-by: Tianyi Zheng <[email protected]> * revert(erosion_operation): Revert erosion_operation * test(jaccard_similarity): Add doctest to test alternative_union * types(newton_raphson): Add typehints to func bodies --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Tianyi Zheng <[email protected]>
1 parent 7618a92 commit 490e645

10 files changed

+65
-36
lines changed

digital_image_processing/morphological_operations/erosion_operation.py

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ def rgb2gray(rgb: np.array) -> np.array:
2121
def gray2binary(gray: np.array) -> np.array:
2222
"""
2323
Return binary image from gray image
24+
2425
>>> gray2binary(np.array([[127, 255, 0]]))
2526
array([[False, True, False]])
2627
>>> gray2binary(np.array([[0]]))

digital_image_processing/rotation/rotation.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ def get_rotation(
1010
) -> np.ndarray:
1111
"""
1212
Get image rotation
13-
:param img: np.array
13+
:param img: np.ndarray
1414
:param pt1: 3x2 list
1515
:param pt2: 3x2 list
1616
:param rows: columns image shape
1717
:param cols: rows image shape
18-
:return: np.array
18+
:return: np.ndarray
1919
"""
2020
matrix = cv2.getAffineTransform(pt1, pt2)
2121
return cv2.warpAffine(img, matrix, (rows, cols))

maths/average_median.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ def median(nums: list) -> int | float:
1919
Returns:
2020
Median.
2121
"""
22-
sorted_list = sorted(nums)
22+
# The sorted function returns list[SupportsRichComparisonT@sorted]
23+
# which does not support `+`
24+
sorted_list: list[int] = sorted(nums)
2325
length = len(sorted_list)
2426
mid_index = length >> 1
2527
return (

maths/euler_modified.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
def euler_modified(
77
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
8-
) -> np.array:
8+
) -> np.ndarray:
99
"""
1010
Calculate solution at each step to an ODE using Euler's Modified Method
1111
The Euler Method is straightforward to implement, but can't give accurate solutions.

maths/gaussian_error_linear_unit.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import numpy as np
1414

1515

16-
def sigmoid(vector: np.array) -> np.array:
16+
def sigmoid(vector: np.ndarray) -> np.ndarray:
1717
"""
1818
Mathematical function sigmoid takes a vector x of K real numbers as input and
1919
returns 1/ (1 + e^-x).
@@ -25,7 +25,7 @@ def sigmoid(vector: np.array) -> np.array:
2525
return 1 / (1 + np.exp(-vector))
2626

2727

28-
def gaussian_error_linear_unit(vector: np.array) -> np.array:
28+
def gaussian_error_linear_unit(vector: np.ndarray) -> np.ndarray:
2929
"""
3030
Implements the Gaussian Error Linear Unit (GELU) function
3131

maths/jaccard_similarity.py

+30-15
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,11 @@
1414
"""
1515

1616

17-
def jaccard_similarity(set_a, set_b, alternative_union=False):
17+
def jaccard_similarity(
18+
set_a: set[str] | list[str] | tuple[str],
19+
set_b: set[str] | list[str] | tuple[str],
20+
alternative_union=False,
21+
):
1822
"""
1923
Finds the jaccard similarity between two sets.
2024
Essentially, its intersection over union.
@@ -37,41 +41,52 @@ def jaccard_similarity(set_a, set_b, alternative_union=False):
3741
>>> set_b = {'c', 'd', 'e', 'f', 'h', 'i'}
3842
>>> jaccard_similarity(set_a, set_b)
3943
0.375
40-
4144
>>> jaccard_similarity(set_a, set_a)
4245
1.0
43-
4446
>>> jaccard_similarity(set_a, set_a, True)
4547
0.5
46-
4748
>>> set_a = ['a', 'b', 'c', 'd', 'e']
4849
>>> set_b = ('c', 'd', 'e', 'f', 'h', 'i')
4950
>>> jaccard_similarity(set_a, set_b)
5051
0.375
52+
>>> set_a = ('c', 'd', 'e', 'f', 'h', 'i')
53+
>>> set_b = ['a', 'b', 'c', 'd', 'e']
54+
>>> jaccard_similarity(set_a, set_b)
55+
0.375
56+
>>> set_a = ('c', 'd', 'e', 'f', 'h', 'i')
57+
>>> set_b = ['a', 'b', 'c', 'd']
58+
>>> jaccard_similarity(set_a, set_b, True)
59+
0.2
60+
>>> set_a = {'a', 'b'}
61+
>>> set_b = ['c', 'd']
62+
>>> jaccard_similarity(set_a, set_b)
63+
Traceback (most recent call last):
64+
...
65+
ValueError: Set a and b must either both be sets or be either a list or a tuple.
5166
"""
5267

5368
if isinstance(set_a, set) and isinstance(set_b, set):
54-
intersection = len(set_a.intersection(set_b))
69+
intersection_length = len(set_a.intersection(set_b))
5570

5671
if alternative_union:
57-
union = len(set_a) + len(set_b)
72+
union_length = len(set_a) + len(set_b)
5873
else:
59-
union = len(set_a.union(set_b))
74+
union_length = len(set_a.union(set_b))
6075

61-
return intersection / union
76+
return intersection_length / union_length
6277

63-
if isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)):
78+
elif isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)):
6479
intersection = [element for element in set_a if element in set_b]
6580

6681
if alternative_union:
67-
union = len(set_a) + len(set_b)
68-
return len(intersection) / union
82+
return len(intersection) / (len(set_a) + len(set_b))
6983
else:
70-
union = set_a + [element for element in set_b if element not in set_a]
84+
# Cast set_a to list because tuples cannot be mutated
85+
union = list(set_a) + [element for element in set_b if element not in set_a]
7186
return len(intersection) / len(union)
72-
73-
return len(intersection) / len(union)
74-
return None
87+
raise ValueError(
88+
"Set a and b must either both be sets or be either a list or a tuple."
89+
)
7590

7691

7792
if __name__ == "__main__":

maths/newton_raphson.py

+22-11
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,35 @@
11
"""
2-
Author: P Shreyas Shetty
3-
Implementation of Newton-Raphson method for solving equations of kind
4-
f(x) = 0. It is an iterative method where solution is found by the expression
5-
x[n+1] = x[n] + f(x[n])/f'(x[n])
6-
If no solution exists, then either the solution will not be found when iteration
7-
limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception
8-
is raised. If iteration limit is reached, try increasing maxiter.
9-
"""
2+
Author: P Shreyas Shetty
3+
Implementation of Newton-Raphson method for solving equations of kind
4+
f(x) = 0. It is an iterative method where solution is found by the expression
5+
x[n+1] = x[n] + f(x[n])/f'(x[n])
6+
If no solution exists, then either the solution will not be found when iteration
7+
limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception
8+
is raised. If iteration limit is reached, try increasing maxiter.
9+
"""
10+
1011
import math as m
12+
from collections.abc import Callable
13+
14+
DerivativeFunc = Callable[[float], float]
1115

1216

13-
def calc_derivative(f, a, h=0.001):
17+
def calc_derivative(f: DerivativeFunc, a: float, h: float = 0.001) -> float:
1418
"""
1519
Calculates derivative at point a for function f using finite difference
1620
method
1721
"""
1822
return (f(a + h) - f(a - h)) / (2 * h)
1923

2024

21-
def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=False):
25+
def newton_raphson(
26+
f: DerivativeFunc,
27+
x0: float = 0,
28+
maxiter: int = 100,
29+
step: float = 0.0001,
30+
maxerror: float = 1e-6,
31+
logsteps: bool = False,
32+
) -> tuple[float, float, list[float]]:
2233
a = x0 # set the initial guess
2334
steps = [a]
2435
error = abs(f(a))
@@ -36,7 +47,7 @@ def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=Fa
3647
if logsteps:
3748
# If logstep is true, then log intermediate steps
3849
return a, error, steps
39-
return a, error
50+
return a, error, []
4051

4152

4253
if __name__ == "__main__":

maths/qr_decomposition.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import numpy as np
22

33

4-
def qr_householder(a):
4+
def qr_householder(a: np.ndarray):
55
"""Return a QR-decomposition of the matrix A using Householder reflection.
66
77
The QR-decomposition decomposes the matrix A of shape (m, n) into an

maths/sigmoid.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import numpy as np
1212

1313

14-
def sigmoid(vector: np.array) -> np.array:
14+
def sigmoid(vector: np.ndarray) -> np.ndarray:
1515
"""
1616
Implements the sigmoid function
1717

maths/tanh.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@
1212
import numpy as np
1313

1414

15-
def tangent_hyperbolic(vector: np.array) -> np.array:
15+
def tangent_hyperbolic(vector: np.ndarray) -> np.ndarray:
1616
"""
1717
Implements the tanh function
1818
1919
Parameters:
20-
vector: np.array
20+
vector: np.ndarray
2121
2222
Returns:
2323
tanh (np.array): The input numpy array after applying tanh.

0 commit comments

Comments
 (0)