Skip to content

Commit f2246ce

Browse files
Enable ruff ICN001 rule (TheAlgorithms#11329)
* Enable ruff ICN001 rule * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent efb7463 commit f2246ce

File tree

8 files changed

+121
-128
lines changed

8 files changed

+121
-128
lines changed

ciphers/hill_cipher.py

+18-20
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838

3939
import string
4040

41-
import numpy
41+
import numpy as np
4242

4343
from maths.greatest_common_divisor import greatest_common_divisor
4444

@@ -49,11 +49,11 @@ class HillCipher:
4949
# i.e. a total of 36 characters
5050

5151
# take x and return x % len(key_string)
52-
modulus = numpy.vectorize(lambda x: x % 36)
52+
modulus = np.vectorize(lambda x: x % 36)
5353

54-
to_int = numpy.vectorize(round)
54+
to_int = np.vectorize(round)
5555

56-
def __init__(self, encrypt_key: numpy.ndarray) -> None:
56+
def __init__(self, encrypt_key: np.ndarray) -> None:
5757
"""
5858
encrypt_key is an NxN numpy array
5959
"""
@@ -63,7 +63,7 @@ def __init__(self, encrypt_key: numpy.ndarray) -> None:
6363

6464
def replace_letters(self, letter: str) -> int:
6565
"""
66-
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
66+
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
6767
>>> hill_cipher.replace_letters('T')
6868
19
6969
>>> hill_cipher.replace_letters('0')
@@ -73,7 +73,7 @@ def replace_letters(self, letter: str) -> int:
7373

7474
def replace_digits(self, num: int) -> str:
7575
"""
76-
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
76+
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
7777
>>> hill_cipher.replace_digits(19)
7878
'T'
7979
>>> hill_cipher.replace_digits(26)
@@ -83,10 +83,10 @@ def replace_digits(self, num: int) -> str:
8383

8484
def check_determinant(self) -> None:
8585
"""
86-
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
86+
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
8787
>>> hill_cipher.check_determinant()
8888
"""
89-
det = round(numpy.linalg.det(self.encrypt_key))
89+
det = round(np.linalg.det(self.encrypt_key))
9090

9191
if det < 0:
9292
det = det % len(self.key_string)
@@ -101,7 +101,7 @@ def check_determinant(self) -> None:
101101

102102
def process_text(self, text: str) -> str:
103103
"""
104-
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
104+
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
105105
>>> hill_cipher.process_text('Testing Hill Cipher')
106106
'TESTINGHILLCIPHERR'
107107
>>> hill_cipher.process_text('hello')
@@ -117,7 +117,7 @@ def process_text(self, text: str) -> str:
117117

118118
def encrypt(self, text: str) -> str:
119119
"""
120-
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
120+
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
121121
>>> hill_cipher.encrypt('testing hill cipher')
122122
'WHXYJOLM9C6XT085LL'
123123
>>> hill_cipher.encrypt('hello')
@@ -129,7 +129,7 @@ def encrypt(self, text: str) -> str:
129129
for i in range(0, len(text) - self.break_key + 1, self.break_key):
130130
batch = text[i : i + self.break_key]
131131
vec = [self.replace_letters(char) for char in batch]
132-
batch_vec = numpy.array([vec]).T
132+
batch_vec = np.array([vec]).T
133133
batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[
134134
0
135135
]
@@ -140,14 +140,14 @@ def encrypt(self, text: str) -> str:
140140

141141
return encrypted
142142

143-
def make_decrypt_key(self) -> numpy.ndarray:
143+
def make_decrypt_key(self) -> np.ndarray:
144144
"""
145-
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
145+
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
146146
>>> hill_cipher.make_decrypt_key()
147147
array([[ 6, 25],
148148
[ 5, 26]])
149149
"""
150-
det = round(numpy.linalg.det(self.encrypt_key))
150+
det = round(np.linalg.det(self.encrypt_key))
151151

152152
if det < 0:
153153
det = det % len(self.key_string)
@@ -158,16 +158,14 @@ def make_decrypt_key(self) -> numpy.ndarray:
158158
break
159159

160160
inv_key = (
161-
det_inv
162-
* numpy.linalg.det(self.encrypt_key)
163-
* numpy.linalg.inv(self.encrypt_key)
161+
det_inv * np.linalg.det(self.encrypt_key) * np.linalg.inv(self.encrypt_key)
164162
)
165163

166164
return self.to_int(self.modulus(inv_key))
167165

168166
def decrypt(self, text: str) -> str:
169167
"""
170-
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
168+
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
171169
>>> hill_cipher.decrypt('WHXYJOLM9C6XT085LL')
172170
'TESTINGHILLCIPHERR'
173171
>>> hill_cipher.decrypt('85FF00')
@@ -180,7 +178,7 @@ def decrypt(self, text: str) -> str:
180178
for i in range(0, len(text) - self.break_key + 1, self.break_key):
181179
batch = text[i : i + self.break_key]
182180
vec = [self.replace_letters(char) for char in batch]
183-
batch_vec = numpy.array([vec]).T
181+
batch_vec = np.array([vec]).T
184182
batch_decrypted = self.modulus(decrypt_key.dot(batch_vec)).T.tolist()[0]
185183
decrypted_batch = "".join(
186184
self.replace_digits(num) for num in batch_decrypted
@@ -199,7 +197,7 @@ def main() -> None:
199197
row = [int(x) for x in input().split()]
200198
hill_matrix.append(row)
201199

202-
hc = HillCipher(numpy.array(hill_matrix))
200+
hc = HillCipher(np.array(hill_matrix))
203201

204202
print("Would you like to encrypt or decrypt some text? (1 or 2)")
205203
option = input("\n1. Encrypt\n2. Decrypt\n")

fractals/julia_sets.py

+26-28
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@
2525
from collections.abc import Callable
2626
from typing import Any
2727

28-
import numpy
29-
from matplotlib import pyplot
28+
import matplotlib.pyplot as plt
29+
import numpy as np
3030

3131
c_cauliflower = 0.25 + 0.0j
3232
c_polynomial_1 = -0.4 + 0.6j
@@ -37,22 +37,20 @@
3737
nb_pixels = 666
3838

3939

40-
def eval_exponential(c_parameter: complex, z_values: numpy.ndarray) -> numpy.ndarray:
40+
def eval_exponential(c_parameter: complex, z_values: np.ndarray) -> np.ndarray:
4141
"""
4242
Evaluate $e^z + c$.
4343
>>> eval_exponential(0, 0)
4444
1.0
45-
>>> abs(eval_exponential(1, numpy.pi*1.j)) < 1e-15
45+
>>> abs(eval_exponential(1, np.pi*1.j)) < 1e-15
4646
True
4747
>>> abs(eval_exponential(1.j, 0)-1-1.j) < 1e-15
4848
True
4949
"""
50-
return numpy.exp(z_values) + c_parameter
50+
return np.exp(z_values) + c_parameter
5151

5252

53-
def eval_quadratic_polynomial(
54-
c_parameter: complex, z_values: numpy.ndarray
55-
) -> numpy.ndarray:
53+
def eval_quadratic_polynomial(c_parameter: complex, z_values: np.ndarray) -> np.ndarray:
5654
"""
5755
>>> eval_quadratic_polynomial(0, 2)
5856
4
@@ -66,7 +64,7 @@ def eval_quadratic_polynomial(
6664
return z_values * z_values + c_parameter
6765

6866

69-
def prepare_grid(window_size: float, nb_pixels: int) -> numpy.ndarray:
67+
def prepare_grid(window_size: float, nb_pixels: int) -> np.ndarray:
7068
"""
7169
Create a grid of complex values of size nb_pixels*nb_pixels with real and
7270
imaginary parts ranging from -window_size to window_size (inclusive).
@@ -77,74 +75,74 @@ def prepare_grid(window_size: float, nb_pixels: int) -> numpy.ndarray:
7775
[ 0.-1.j, 0.+0.j, 0.+1.j],
7876
[ 1.-1.j, 1.+0.j, 1.+1.j]])
7977
"""
80-
x = numpy.linspace(-window_size, window_size, nb_pixels)
78+
x = np.linspace(-window_size, window_size, nb_pixels)
8179
x = x.reshape((nb_pixels, 1))
82-
y = numpy.linspace(-window_size, window_size, nb_pixels)
80+
y = np.linspace(-window_size, window_size, nb_pixels)
8381
y = y.reshape((1, nb_pixels))
8482
return x + 1.0j * y
8583

8684

8785
def iterate_function(
88-
eval_function: Callable[[Any, numpy.ndarray], numpy.ndarray],
86+
eval_function: Callable[[Any, np.ndarray], np.ndarray],
8987
function_params: Any,
9088
nb_iterations: int,
91-
z_0: numpy.ndarray,
89+
z_0: np.ndarray,
9290
infinity: float | None = None,
93-
) -> numpy.ndarray:
91+
) -> np.ndarray:
9492
"""
9593
Iterate the function "eval_function" exactly nb_iterations times.
9694
The first argument of the function is a parameter which is contained in
9795
function_params. The variable z_0 is an array that contains the initial
9896
values to iterate from.
9997
This function returns the final iterates.
10098
101-
>>> iterate_function(eval_quadratic_polynomial, 0, 3, numpy.array([0,1,2])).shape
99+
>>> iterate_function(eval_quadratic_polynomial, 0, 3, np.array([0,1,2])).shape
102100
(3,)
103-
>>> numpy.round(iterate_function(eval_quadratic_polynomial,
101+
>>> np.round(iterate_function(eval_quadratic_polynomial,
104102
... 0,
105103
... 3,
106-
... numpy.array([0,1,2]))[0])
104+
... np.array([0,1,2]))[0])
107105
0j
108-
>>> numpy.round(iterate_function(eval_quadratic_polynomial,
106+
>>> np.round(iterate_function(eval_quadratic_polynomial,
109107
... 0,
110108
... 3,
111-
... numpy.array([0,1,2]))[1])
109+
... np.array([0,1,2]))[1])
112110
(1+0j)
113-
>>> numpy.round(iterate_function(eval_quadratic_polynomial,
111+
>>> np.round(iterate_function(eval_quadratic_polynomial,
114112
... 0,
115113
... 3,
116-
... numpy.array([0,1,2]))[2])
114+
... np.array([0,1,2]))[2])
117115
(256+0j)
118116
"""
119117

120118
z_n = z_0.astype("complex64")
121119
for _ in range(nb_iterations):
122120
z_n = eval_function(function_params, z_n)
123121
if infinity is not None:
124-
numpy.nan_to_num(z_n, copy=False, nan=infinity)
125-
z_n[abs(z_n) == numpy.inf] = infinity
122+
np.nan_to_num(z_n, copy=False, nan=infinity)
123+
z_n[abs(z_n) == np.inf] = infinity
126124
return z_n
127125

128126

129127
def show_results(
130128
function_label: str,
131129
function_params: Any,
132130
escape_radius: float,
133-
z_final: numpy.ndarray,
131+
z_final: np.ndarray,
134132
) -> None:
135133
"""
136134
Plots of whether the absolute value of z_final is greater than
137135
the value of escape_radius. Adds the function_label and function_params to
138136
the title.
139137
140-
>>> show_results('80', 0, 1, numpy.array([[0,1,.5],[.4,2,1.1],[.2,1,1.3]]))
138+
>>> show_results('80', 0, 1, np.array([[0,1,.5],[.4,2,1.1],[.2,1,1.3]]))
141139
"""
142140

143141
abs_z_final = (abs(z_final)).transpose()
144142
abs_z_final[:, :] = abs_z_final[::-1, :]
145-
pyplot.matshow(abs_z_final < escape_radius)
146-
pyplot.title(f"Julia set of ${function_label}$, $c={function_params}$")
147-
pyplot.show()
143+
plt.matshow(abs_z_final < escape_radius)
144+
plt.title(f"Julia set of ${function_label}$, $c={function_params}$")
145+
plt.show()
148146

149147

150148
def ignore_overflow_warnings() -> None:

fractals/koch_snowflake.py

+17-17
Original file line numberDiff line numberDiff line change
@@ -22,25 +22,25 @@
2222

2323
from __future__ import annotations
2424

25-
import matplotlib.pyplot as plt # type: ignore
26-
import numpy
25+
import matplotlib.pyplot as plt
26+
import numpy as np
2727

2828
# initial triangle of Koch snowflake
29-
VECTOR_1 = numpy.array([0, 0])
30-
VECTOR_2 = numpy.array([0.5, 0.8660254])
31-
VECTOR_3 = numpy.array([1, 0])
29+
VECTOR_1 = np.array([0, 0])
30+
VECTOR_2 = np.array([0.5, 0.8660254])
31+
VECTOR_3 = np.array([1, 0])
3232
INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
3333

3434
# uncomment for simple Koch curve instead of Koch snowflake
3535
# INITIAL_VECTORS = [VECTOR_1, VECTOR_3]
3636

3737

38-
def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]:
38+
def iterate(initial_vectors: list[np.ndarray], steps: int) -> list[np.ndarray]:
3939
"""
4040
Go through the number of iterations determined by the argument "steps".
4141
Be careful with high values (above 5) since the time to calculate increases
4242
exponentially.
43-
>>> iterate([numpy.array([0, 0]), numpy.array([1, 0])], 1)
43+
>>> iterate([np.array([0, 0]), np.array([1, 0])], 1)
4444
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
4545
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
4646
"""
@@ -50,13 +50,13 @@ def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndar
5050
return vectors
5151

5252

53-
def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]:
53+
def iteration_step(vectors: list[np.ndarray]) -> list[np.ndarray]:
5454
"""
5555
Loops through each pair of adjacent vectors. Each line between two adjacent
5656
vectors is divided into 4 segments by adding 3 additional vectors in-between
5757
the original two vectors. The vector in the middle is constructed through a
5858
60 degree rotation so it is bent outwards.
59-
>>> iteration_step([numpy.array([0, 0]), numpy.array([1, 0])])
59+
>>> iteration_step([np.array([0, 0]), np.array([1, 0])])
6060
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
6161
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
6262
"""
@@ -74,22 +74,22 @@ def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]:
7474
return new_vectors
7575

7676

77-
def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray:
77+
def rotate(vector: np.ndarray, angle_in_degrees: float) -> np.ndarray:
7878
"""
7979
Standard rotation of a 2D vector with a rotation matrix
8080
(see https://en.wikipedia.org/wiki/Rotation_matrix )
81-
>>> rotate(numpy.array([1, 0]), 60)
81+
>>> rotate(np.array([1, 0]), 60)
8282
array([0.5 , 0.8660254])
83-
>>> rotate(numpy.array([1, 0]), 90)
83+
>>> rotate(np.array([1, 0]), 90)
8484
array([6.123234e-17, 1.000000e+00])
8585
"""
86-
theta = numpy.radians(angle_in_degrees)
87-
c, s = numpy.cos(theta), numpy.sin(theta)
88-
rotation_matrix = numpy.array(((c, -s), (s, c)))
89-
return numpy.dot(rotation_matrix, vector)
86+
theta = np.radians(angle_in_degrees)
87+
c, s = np.cos(theta), np.sin(theta)
88+
rotation_matrix = np.array(((c, -s), (s, c)))
89+
return np.dot(rotation_matrix, vector)
9090

9191

92-
def plot(vectors: list[numpy.ndarray]) -> None:
92+
def plot(vectors: list[np.ndarray]) -> None:
9393
"""
9494
Utility function to plot the vectors using matplotlib.pyplot
9595
No doctest was implemented since this function does not have a return value

graphics/bezier_curve.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def plot_curve(self, step_size: float = 0.01):
7878
step_size: defines the step(s) at which to evaluate the Bezier curve.
7979
The smaller the step size, the finer the curve produced.
8080
"""
81-
from matplotlib import pyplot as plt # type: ignore
81+
from matplotlib import pyplot as plt
8282

8383
to_plot_x: list[float] = [] # x coordinates of points to plot
8484
to_plot_y: list[float] = [] # y coordinates of points to plot

machine_learning/gradient_descent.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
function.
44
"""
55

6-
import numpy
6+
import numpy as np
77

88
# List of input, output pairs
99
train_data = (
@@ -116,7 +116,7 @@ def run_gradient_descent():
116116
temp_parameter_vector[i] = (
117117
parameter_vector[i] - LEARNING_RATE * cost_derivative
118118
)
119-
if numpy.allclose(
119+
if np.allclose(
120120
parameter_vector,
121121
temp_parameter_vector,
122122
atol=absolute_error_limit,

0 commit comments

Comments
 (0)