Skip to content

Commit 4b79d77

Browse files
cclaussdhruvmanilapre-commit-ci[bot]
authored
Add more ruff rules (TheAlgorithms#8767)
* Add more ruff rules * Add more ruff rules * pre-commit: Update ruff v0.0.269 -> v0.0.270 * Apply suggestions from code review * Fix doctest * Fix doctest (ignore whitespace) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent dd3b499 commit 4b79d77

File tree

67 files changed

+349
-223
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+349
-223
lines changed

.pre-commit-config.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ repos:
1616
- id: auto-walrus
1717

1818
- repo: https://github.com/charliermarsh/ruff-pre-commit
19-
rev: v0.0.269
19+
rev: v0.0.270
2020
hooks:
2121
- id: ruff
2222

arithmetic_analysis/jacobi_iteration_method.py

+18-12
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ def jacobi_iteration_method(
4949
>>> constant = np.array([[2], [-6]])
5050
>>> init_val = [0.5, -0.5, -0.5]
5151
>>> iterations = 3
52-
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
52+
>>> jacobi_iteration_method(
53+
... coefficient, constant, init_val, iterations
54+
... ) # doctest: +NORMALIZE_WHITESPACE
5355
Traceback (most recent call last):
5456
...
5557
ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but
@@ -59,7 +61,9 @@ def jacobi_iteration_method(
5961
>>> constant = np.array([[2], [-6], [-4]])
6062
>>> init_val = [0.5, -0.5]
6163
>>> iterations = 3
62-
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
64+
>>> jacobi_iteration_method(
65+
... coefficient, constant, init_val, iterations
66+
... ) # doctest: +NORMALIZE_WHITESPACE
6367
Traceback (most recent call last):
6468
...
6569
ValueError: Number of initial values must be equal to number of rows in coefficient
@@ -79,24 +83,26 @@ def jacobi_iteration_method(
7983
rows2, cols2 = constant_matrix.shape
8084

8185
if rows1 != cols1:
82-
raise ValueError(
83-
f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
84-
)
86+
msg = f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
87+
raise ValueError(msg)
8588

8689
if cols2 != 1:
87-
raise ValueError(f"Constant matrix must be nx1 but received {rows2}x{cols2}")
90+
msg = f"Constant matrix must be nx1 but received {rows2}x{cols2}"
91+
raise ValueError(msg)
8892

8993
if rows1 != rows2:
90-
raise ValueError(
91-
f"""Coefficient and constant matrices dimensions must be nxn and nx1 but
92-
received {rows1}x{cols1} and {rows2}x{cols2}"""
94+
msg = (
95+
"Coefficient and constant matrices dimensions must be nxn and nx1 but "
96+
f"received {rows1}x{cols1} and {rows2}x{cols2}"
9397
)
98+
raise ValueError(msg)
9499

95100
if len(init_val) != rows1:
96-
raise ValueError(
97-
f"""Number of initial values must be equal to number of rows in coefficient
98-
matrix but received {len(init_val)} and {rows1}"""
101+
msg = (
102+
"Number of initial values must be equal to number of rows in coefficient "
103+
f"matrix but received {len(init_val)} and {rows1}"
99104
)
105+
raise ValueError(msg)
100106

101107
if iterations <= 0:
102108
raise ValueError("Iterations must be at least 1")

arithmetic_analysis/lu_decomposition.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,11 @@ def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray
8080
# Ensure that table is a square array
8181
rows, columns = np.shape(table)
8282
if rows != columns:
83-
raise ValueError(
84-
f"'table' has to be of square shaped array but got a "
83+
msg = (
84+
"'table' has to be of square shaped array but got a "
8585
f"{rows}x{columns} array:\n{table}"
8686
)
87+
raise ValueError(msg)
8788

8889
lower = np.zeros((rows, columns))
8990
upper = np.zeros((rows, columns))

audio_filters/iir_filter.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,18 @@ def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None
5050
a_coeffs = [1.0, *a_coeffs]
5151

5252
if len(a_coeffs) != self.order + 1:
53-
raise ValueError(
54-
f"Expected a_coeffs to have {self.order + 1} elements for {self.order}"
55-
f"-order filter, got {len(a_coeffs)}"
53+
msg = (
54+
f"Expected a_coeffs to have {self.order + 1} elements "
55+
f"for {self.order}-order filter, got {len(a_coeffs)}"
5656
)
57+
raise ValueError(msg)
5758

5859
if len(b_coeffs) != self.order + 1:
59-
raise ValueError(
60-
f"Expected b_coeffs to have {self.order + 1} elements for {self.order}"
61-
f"-order filter, got {len(a_coeffs)}"
60+
msg = (
61+
f"Expected b_coeffs to have {self.order + 1} elements "
62+
f"for {self.order}-order filter, got {len(a_coeffs)}"
6263
)
64+
raise ValueError(msg)
6365

6466
self.a_coeffs = a_coeffs
6567
self.b_coeffs = b_coeffs

backtracking/knight_tour.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,8 @@ def open_knight_tour(n: int) -> list[list[int]]:
9191
return board
9292
board[i][j] = 0
9393

94-
raise ValueError(f"Open Kight Tour cannot be performed on a board of size {n}")
94+
msg = f"Open Kight Tour cannot be performed on a board of size {n}"
95+
raise ValueError(msg)
9596

9697

9798
if __name__ == "__main__":

bit_manipulation/reverse_bits.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@ def get_reverse_bit_string(number: int) -> str:
1414
TypeError: operation can not be conducted on a object of type str
1515
"""
1616
if not isinstance(number, int):
17-
raise TypeError(
17+
msg = (
1818
"operation can not be conducted on a object of type "
1919
f"{type(number).__name__}"
2020
)
21+
raise TypeError(msg)
2122
bit_string = ""
2223
for _ in range(0, 32):
2324
bit_string += str(number % 2)

ciphers/base64.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,8 @@ def base64_encode(data: bytes) -> bytes:
3434
"""
3535
# Make sure the supplied data is a bytes-like object
3636
if not isinstance(data, bytes):
37-
raise TypeError(
38-
f"a bytes-like object is required, not '{data.__class__.__name__}'"
39-
)
37+
msg = f"a bytes-like object is required, not '{data.__class__.__name__}'"
38+
raise TypeError(msg)
4039

4140
binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data)
4241

@@ -88,10 +87,11 @@ def base64_decode(encoded_data: str) -> bytes:
8887
"""
8988
# Make sure encoded_data is either a string or a bytes-like object
9089
if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):
91-
raise TypeError(
92-
"argument should be a bytes-like object or ASCII string, not "
93-
f"'{encoded_data.__class__.__name__}'"
90+
msg = (
91+
"argument should be a bytes-like object or ASCII string, "
92+
f"not '{encoded_data.__class__.__name__}'"
9493
)
94+
raise TypeError(msg)
9595

9696
# In case encoded_data is a bytes-like object, make sure it contains only
9797
# ASCII characters so we convert it to a string object

ciphers/beaufort_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from string import ascii_uppercase
66

77
dict1 = {char: i for i, char in enumerate(ascii_uppercase)}
8-
dict2 = {i: char for i, char in enumerate(ascii_uppercase)}
8+
dict2 = dict(enumerate(ascii_uppercase))
99

1010

1111
# This function generates the key in

ciphers/cryptomath_module.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ def gcd(a: int, b: int) -> int:
66

77
def find_mod_inverse(a: int, m: int) -> int:
88
if gcd(a, m) != 1:
9-
raise ValueError(f"mod inverse of {a!r} and {m!r} does not exist")
9+
msg = f"mod inverse of {a!r} and {m!r} does not exist"
10+
raise ValueError(msg)
1011
u1, u2, u3 = 1, 0, a
1112
v1, v2, v3 = 0, 1, m
1213
while v3 != 0:

ciphers/enigma_machine2.py

+16-14
Original file line numberDiff line numberDiff line change
@@ -87,22 +87,20 @@ def _validator(
8787
# Checks if there are 3 unique rotors
8888

8989
if (unique_rotsel := len(set(rotsel))) < 3:
90-
raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})")
90+
msg = f"Please use 3 unique rotors (not {unique_rotsel})"
91+
raise Exception(msg)
9192

9293
# Checks if rotor positions are valid
9394
rotorpos1, rotorpos2, rotorpos3 = rotpos
9495
if not 0 < rotorpos1 <= len(abc):
95-
raise ValueError(
96-
"First rotor position is not within range of 1..26 (" f"{rotorpos1}"
97-
)
96+
msg = f"First rotor position is not within range of 1..26 ({rotorpos1}"
97+
raise ValueError(msg)
9898
if not 0 < rotorpos2 <= len(abc):
99-
raise ValueError(
100-
"Second rotor position is not within range of 1..26 (" f"{rotorpos2})"
101-
)
99+
msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})"
100+
raise ValueError(msg)
102101
if not 0 < rotorpos3 <= len(abc):
103-
raise ValueError(
104-
"Third rotor position is not within range of 1..26 (" f"{rotorpos3})"
105-
)
102+
msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})"
103+
raise ValueError(msg)
106104

107105
# Validates string and returns dict
108106
pbdict = _plugboard(pb)
@@ -130,9 +128,11 @@ def _plugboard(pbstring: str) -> dict[str, str]:
130128
# a) is type string
131129
# b) has even length (so pairs can be made)
132130
if not isinstance(pbstring, str):
133-
raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})")
131+
msg = f"Plugboard setting isn't type string ({type(pbstring)})"
132+
raise TypeError(msg)
134133
elif len(pbstring) % 2 != 0:
135-
raise Exception(f"Odd number of symbols ({len(pbstring)})")
134+
msg = f"Odd number of symbols ({len(pbstring)})"
135+
raise Exception(msg)
136136
elif pbstring == "":
137137
return {}
138138

@@ -142,9 +142,11 @@ def _plugboard(pbstring: str) -> dict[str, str]:
142142
tmppbl = set()
143143
for i in pbstring:
144144
if i not in abc:
145-
raise Exception(f"'{i}' not in list of symbols")
145+
msg = f"'{i}' not in list of symbols"
146+
raise Exception(msg)
146147
elif i in tmppbl:
147-
raise Exception(f"Duplicate symbol ({i})")
148+
msg = f"Duplicate symbol ({i})"
149+
raise Exception(msg)
148150
else:
149151
tmppbl.add(i)
150152
del tmppbl

ciphers/hill_cipher.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,11 @@ def check_determinant(self) -> None:
104104

105105
req_l = len(self.key_string)
106106
if greatest_common_divisor(det, len(self.key_string)) != 1:
107-
raise ValueError(
108-
f"determinant modular {req_l} of encryption key({det}) is not co prime "
109-
f"w.r.t {req_l}.\nTry another key."
107+
msg = (
108+
f"determinant modular {req_l} of encryption key({det}) "
109+
f"is not co prime w.r.t {req_l}.\nTry another key."
110110
)
111+
raise ValueError(msg)
111112

112113
def process_text(self, text: str) -> str:
113114
"""

conversions/astronomical_length_scale_conversion.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -77,15 +77,17 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
7777
to_sanitized = UNIT_SYMBOL.get(to_sanitized, to_sanitized)
7878

7979
if from_sanitized not in METRIC_CONVERSION:
80-
raise ValueError(
80+
msg = (
8181
f"Invalid 'from_type' value: {from_type!r}.\n"
8282
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
8383
)
84+
raise ValueError(msg)
8485
if to_sanitized not in METRIC_CONVERSION:
85-
raise ValueError(
86+
msg = (
8687
f"Invalid 'to_type' value: {to_type!r}.\n"
8788
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
8889
)
90+
raise ValueError(msg)
8991
from_exponent = METRIC_CONVERSION[from_sanitized]
9092
to_exponent = METRIC_CONVERSION[to_sanitized]
9193
exponent = 1

conversions/length_conversion.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -104,15 +104,17 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
104104
new_to = to_type.lower().rstrip("s")
105105
new_to = TYPE_CONVERSION.get(new_to, new_to)
106106
if new_from not in METRIC_CONVERSION:
107-
raise ValueError(
107+
msg = (
108108
f"Invalid 'from_type' value: {from_type!r}.\n"
109109
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
110110
)
111+
raise ValueError(msg)
111112
if new_to not in METRIC_CONVERSION:
112-
raise ValueError(
113+
msg = (
113114
f"Invalid 'to_type' value: {to_type!r}.\n"
114115
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
115116
)
117+
raise ValueError(msg)
116118
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
117119

118120

conversions/speed_conversions.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,11 @@ def convert_speed(speed: float, unit_from: str, unit_to: str) -> float:
5757
115.078
5858
"""
5959
if unit_to not in speed_chart or unit_from not in speed_chart_inverse:
60-
raise ValueError(
60+
msg = (
6161
f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n"
6262
f"Valid values are: {', '.join(speed_chart_inverse)}"
6363
)
64+
raise ValueError(msg)
6465
return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3)
6566

6667

conversions/weight_conversion.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -299,10 +299,11 @@ def weight_conversion(from_type: str, to_type: str, value: float) -> float:
299299
1.999999998903455
300300
"""
301301
if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART:
302-
raise ValueError(
302+
msg = (
303303
f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"
304304
f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}"
305305
)
306+
raise ValueError(msg)
306307
return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type]
307308

308309

data_structures/binary_tree/binary_search_tree_recursive.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,8 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
7777
elif label > node.label:
7878
node.right = self._put(node.right, label, node)
7979
else:
80-
raise Exception(f"Node with label {label} already exists")
80+
msg = f"Node with label {label} already exists"
81+
raise Exception(msg)
8182

8283
return node
8384

@@ -100,7 +101,8 @@ def search(self, label: int) -> Node:
100101

101102
def _search(self, node: Node | None, label: int) -> Node:
102103
if node is None:
103-
raise Exception(f"Node with label {label} does not exist")
104+
msg = f"Node with label {label} does not exist"
105+
raise Exception(msg)
104106
else:
105107
if label < node.label:
106108
node = self._search(node.left, label)

data_structures/binary_tree/binary_tree_mirror.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict:
3131
if not binary_tree:
3232
raise ValueError("binary tree cannot be empty")
3333
if root not in binary_tree:
34-
raise ValueError(f"root {root} is not present in the binary_tree")
34+
msg = f"root {root} is not present in the binary_tree"
35+
raise ValueError(msg)
3536
binary_tree_mirror_dictionary = dict(binary_tree)
3637
binary_tree_mirror_dict(binary_tree_mirror_dictionary, root)
3738
return binary_tree_mirror_dictionary

data_structures/disjoint_set/disjoint_set.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,8 @@ def find_python_set(node: Node) -> set:
5656
for s in sets:
5757
if node.data in s:
5858
return s
59-
raise ValueError(f"{node.data} is not in {sets}")
59+
msg = f"{node.data} is not in {sets}"
60+
raise ValueError(msg)
6061

6162

6263
def test_disjoint_set() -> None:

data_structures/linked_list/circular_linked_list.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -94,25 +94,25 @@ def test_circular_linked_list() -> None:
9494

9595
try:
9696
circular_linked_list.delete_front()
97-
raise AssertionError() # This should not happen
97+
raise AssertionError # This should not happen
9898
except IndexError:
9999
assert True # This should happen
100100

101101
try:
102102
circular_linked_list.delete_tail()
103-
raise AssertionError() # This should not happen
103+
raise AssertionError # This should not happen
104104
except IndexError:
105105
assert True # This should happen
106106

107107
try:
108108
circular_linked_list.delete_nth(-1)
109-
raise AssertionError()
109+
raise AssertionError
110110
except IndexError:
111111
assert True
112112

113113
try:
114114
circular_linked_list.delete_nth(0)
115-
raise AssertionError()
115+
raise AssertionError
116116
except IndexError:
117117
assert True
118118

0 commit comments

Comments
 (0)