Add more ruff rules (#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>
This commit is contained in:
Christian Clauss 2023-05-26 09:34:17 +02:00 committed by GitHub
parent dd3b499bfa
commit 4b79d771cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
67 changed files with 349 additions and 223 deletions

View File

@ -16,7 +16,7 @@ repos:
- id: auto-walrus - id: auto-walrus
- repo: https://github.com/charliermarsh/ruff-pre-commit - repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.269 rev: v0.0.270
hooks: hooks:
- id: ruff - id: ruff

View File

@ -49,7 +49,9 @@ def jacobi_iteration_method(
>>> constant = np.array([[2], [-6]]) >>> constant = np.array([[2], [-6]])
>>> init_val = [0.5, -0.5, -0.5] >>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 3 >>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations) >>> jacobi_iteration_method(
... coefficient, constant, init_val, iterations
... ) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but
@ -59,7 +61,9 @@ def jacobi_iteration_method(
>>> constant = np.array([[2], [-6], [-4]]) >>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5] >>> init_val = [0.5, -0.5]
>>> iterations = 3 >>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations) >>> jacobi_iteration_method(
... coefficient, constant, init_val, iterations
... ) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValueError: Number of initial values must be equal to number of rows in coefficient ValueError: Number of initial values must be equal to number of rows in coefficient
@ -79,24 +83,26 @@ def jacobi_iteration_method(
rows2, cols2 = constant_matrix.shape rows2, cols2 = constant_matrix.shape
if rows1 != cols1: if rows1 != cols1:
raise ValueError( msg = f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}" raise ValueError(msg)
)
if cols2 != 1: if cols2 != 1:
raise ValueError(f"Constant matrix must be nx1 but received {rows2}x{cols2}") msg = f"Constant matrix must be nx1 but received {rows2}x{cols2}"
raise ValueError(msg)
if rows1 != rows2: if rows1 != rows2:
raise ValueError( msg = (
f"""Coefficient and constant matrices dimensions must be nxn and nx1 but "Coefficient and constant matrices dimensions must be nxn and nx1 but "
received {rows1}x{cols1} and {rows2}x{cols2}""" f"received {rows1}x{cols1} and {rows2}x{cols2}"
) )
raise ValueError(msg)
if len(init_val) != rows1: if len(init_val) != rows1:
raise ValueError( msg = (
f"""Number of initial values must be equal to number of rows in coefficient "Number of initial values must be equal to number of rows in coefficient "
matrix but received {len(init_val)} and {rows1}""" f"matrix but received {len(init_val)} and {rows1}"
) )
raise ValueError(msg)
if iterations <= 0: if iterations <= 0:
raise ValueError("Iterations must be at least 1") raise ValueError("Iterations must be at least 1")

View File

@ -80,10 +80,11 @@ def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray
# Ensure that table is a square array # Ensure that table is a square array
rows, columns = np.shape(table) rows, columns = np.shape(table)
if rows != columns: if rows != columns:
raise ValueError( msg = (
f"'table' has to be of square shaped array but got a " "'table' has to be of square shaped array but got a "
f"{rows}x{columns} array:\n{table}" f"{rows}x{columns} array:\n{table}"
) )
raise ValueError(msg)
lower = np.zeros((rows, columns)) lower = np.zeros((rows, columns))
upper = np.zeros((rows, columns)) upper = np.zeros((rows, columns))

View File

@ -50,16 +50,18 @@ class IIRFilter:
a_coeffs = [1.0, *a_coeffs] a_coeffs = [1.0, *a_coeffs]
if len(a_coeffs) != self.order + 1: if len(a_coeffs) != self.order + 1:
raise ValueError( msg = (
f"Expected a_coeffs to have {self.order + 1} elements for {self.order}" f"Expected a_coeffs to have {self.order + 1} elements "
f"-order filter, got {len(a_coeffs)}" f"for {self.order}-order filter, got {len(a_coeffs)}"
) )
raise ValueError(msg)
if len(b_coeffs) != self.order + 1: if len(b_coeffs) != self.order + 1:
raise ValueError( msg = (
f"Expected b_coeffs to have {self.order + 1} elements for {self.order}" f"Expected b_coeffs to have {self.order + 1} elements "
f"-order filter, got {len(a_coeffs)}" f"for {self.order}-order filter, got {len(a_coeffs)}"
) )
raise ValueError(msg)
self.a_coeffs = a_coeffs self.a_coeffs = a_coeffs
self.b_coeffs = b_coeffs self.b_coeffs = b_coeffs

View File

@ -91,7 +91,8 @@ def open_knight_tour(n: int) -> list[list[int]]:
return board return board
board[i][j] = 0 board[i][j] = 0
raise ValueError(f"Open Kight Tour cannot be performed on a board of size {n}") msg = f"Open Kight Tour cannot be performed on a board of size {n}"
raise ValueError(msg)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -14,10 +14,11 @@ def get_reverse_bit_string(number: int) -> str:
TypeError: operation can not be conducted on a object of type str TypeError: operation can not be conducted on a object of type str
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError( msg = (
"operation can not be conducted on a object of type " "operation can not be conducted on a object of type "
f"{type(number).__name__}" f"{type(number).__name__}"
) )
raise TypeError(msg)
bit_string = "" bit_string = ""
for _ in range(0, 32): for _ in range(0, 32):
bit_string += str(number % 2) bit_string += str(number % 2)

View File

@ -34,9 +34,8 @@ def base64_encode(data: bytes) -> bytes:
""" """
# Make sure the supplied data is a bytes-like object # Make sure the supplied data is a bytes-like object
if not isinstance(data, bytes): if not isinstance(data, bytes):
raise TypeError( msg = f"a bytes-like object is required, not '{data.__class__.__name__}'"
f"a bytes-like object is required, not '{data.__class__.__name__}'" raise TypeError(msg)
)
binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data) binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data)
@ -88,10 +87,11 @@ def base64_decode(encoded_data: str) -> bytes:
""" """
# Make sure encoded_data is either a string or a bytes-like object # Make sure encoded_data is either a string or a bytes-like object
if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str): if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):
raise TypeError( msg = (
"argument should be a bytes-like object or ASCII string, not " "argument should be a bytes-like object or ASCII string, "
f"'{encoded_data.__class__.__name__}'" f"not '{encoded_data.__class__.__name__}'"
) )
raise TypeError(msg)
# In case encoded_data is a bytes-like object, make sure it contains only # In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object # ASCII characters so we convert it to a string object

View File

@ -5,7 +5,7 @@ Author: Mohit Radadiya
from string import ascii_uppercase from string import ascii_uppercase
dict1 = {char: i for i, char in enumerate(ascii_uppercase)} dict1 = {char: i for i, char in enumerate(ascii_uppercase)}
dict2 = {i: char for i, char in enumerate(ascii_uppercase)} dict2 = dict(enumerate(ascii_uppercase))
# This function generates the key in # This function generates the key in

View File

@ -6,7 +6,8 @@ def gcd(a: int, b: int) -> int:
def find_mod_inverse(a: int, m: int) -> int: def find_mod_inverse(a: int, m: int) -> int:
if gcd(a, m) != 1: if gcd(a, m) != 1:
raise ValueError(f"mod inverse of {a!r} and {m!r} does not exist") msg = f"mod inverse of {a!r} and {m!r} does not exist"
raise ValueError(msg)
u1, u2, u3 = 1, 0, a u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m v1, v2, v3 = 0, 1, m
while v3 != 0: while v3 != 0:

View File

@ -87,22 +87,20 @@ def _validator(
# Checks if there are 3 unique rotors # Checks if there are 3 unique rotors
if (unique_rotsel := len(set(rotsel))) < 3: if (unique_rotsel := len(set(rotsel))) < 3:
raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})") msg = f"Please use 3 unique rotors (not {unique_rotsel})"
raise Exception(msg)
# Checks if rotor positions are valid # Checks if rotor positions are valid
rotorpos1, rotorpos2, rotorpos3 = rotpos rotorpos1, rotorpos2, rotorpos3 = rotpos
if not 0 < rotorpos1 <= len(abc): if not 0 < rotorpos1 <= len(abc):
raise ValueError( msg = f"First rotor position is not within range of 1..26 ({rotorpos1}"
"First rotor position is not within range of 1..26 (" f"{rotorpos1}" raise ValueError(msg)
)
if not 0 < rotorpos2 <= len(abc): if not 0 < rotorpos2 <= len(abc):
raise ValueError( msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})"
"Second rotor position is not within range of 1..26 (" f"{rotorpos2})" raise ValueError(msg)
)
if not 0 < rotorpos3 <= len(abc): if not 0 < rotorpos3 <= len(abc):
raise ValueError( msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})"
"Third rotor position is not within range of 1..26 (" f"{rotorpos3})" raise ValueError(msg)
)
# Validates string and returns dict # Validates string and returns dict
pbdict = _plugboard(pb) pbdict = _plugboard(pb)
@ -130,9 +128,11 @@ def _plugboard(pbstring: str) -> dict[str, str]:
# a) is type string # a) is type string
# b) has even length (so pairs can be made) # b) has even length (so pairs can be made)
if not isinstance(pbstring, str): if not isinstance(pbstring, str):
raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})") msg = f"Plugboard setting isn't type string ({type(pbstring)})"
raise TypeError(msg)
elif len(pbstring) % 2 != 0: elif len(pbstring) % 2 != 0:
raise Exception(f"Odd number of symbols ({len(pbstring)})") msg = f"Odd number of symbols ({len(pbstring)})"
raise Exception(msg)
elif pbstring == "": elif pbstring == "":
return {} return {}
@ -142,9 +142,11 @@ def _plugboard(pbstring: str) -> dict[str, str]:
tmppbl = set() tmppbl = set()
for i in pbstring: for i in pbstring:
if i not in abc: if i not in abc:
raise Exception(f"'{i}' not in list of symbols") msg = f"'{i}' not in list of symbols"
raise Exception(msg)
elif i in tmppbl: elif i in tmppbl:
raise Exception(f"Duplicate symbol ({i})") msg = f"Duplicate symbol ({i})"
raise Exception(msg)
else: else:
tmppbl.add(i) tmppbl.add(i)
del tmppbl del tmppbl

View File

@ -104,10 +104,11 @@ class HillCipher:
req_l = len(self.key_string) req_l = len(self.key_string)
if greatest_common_divisor(det, len(self.key_string)) != 1: if greatest_common_divisor(det, len(self.key_string)) != 1:
raise ValueError( msg = (
f"determinant modular {req_l} of encryption key({det}) is not co prime " f"determinant modular {req_l} of encryption key({det}) "
f"w.r.t {req_l}.\nTry another key." f"is not co prime w.r.t {req_l}.\nTry another key."
) )
raise ValueError(msg)
def process_text(self, text: str) -> str: def process_text(self, text: str) -> str:
""" """

View File

@ -77,15 +77,17 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
to_sanitized = UNIT_SYMBOL.get(to_sanitized, to_sanitized) to_sanitized = UNIT_SYMBOL.get(to_sanitized, to_sanitized)
if from_sanitized not in METRIC_CONVERSION: if from_sanitized not in METRIC_CONVERSION:
raise ValueError( msg = (
f"Invalid 'from_type' value: {from_type!r}.\n" f"Invalid 'from_type' value: {from_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
) )
raise ValueError(msg)
if to_sanitized not in METRIC_CONVERSION: if to_sanitized not in METRIC_CONVERSION:
raise ValueError( msg = (
f"Invalid 'to_type' value: {to_type!r}.\n" f"Invalid 'to_type' value: {to_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
) )
raise ValueError(msg)
from_exponent = METRIC_CONVERSION[from_sanitized] from_exponent = METRIC_CONVERSION[from_sanitized]
to_exponent = METRIC_CONVERSION[to_sanitized] to_exponent = METRIC_CONVERSION[to_sanitized]
exponent = 1 exponent = 1

View File

@ -104,15 +104,17 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
new_to = to_type.lower().rstrip("s") new_to = to_type.lower().rstrip("s")
new_to = TYPE_CONVERSION.get(new_to, new_to) new_to = TYPE_CONVERSION.get(new_to, new_to)
if new_from not in METRIC_CONVERSION: if new_from not in METRIC_CONVERSION:
raise ValueError( msg = (
f"Invalid 'from_type' value: {from_type!r}.\n" f"Invalid 'from_type' value: {from_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
) )
raise ValueError(msg)
if new_to not in METRIC_CONVERSION: if new_to not in METRIC_CONVERSION:
raise ValueError( msg = (
f"Invalid 'to_type' value: {to_type!r}.\n" f"Invalid 'to_type' value: {to_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
) )
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to

View File

@ -57,10 +57,11 @@ def convert_speed(speed: float, unit_from: str, unit_to: str) -> float:
115.078 115.078
""" """
if unit_to not in speed_chart or unit_from not in speed_chart_inverse: if unit_to not in speed_chart or unit_from not in speed_chart_inverse:
raise ValueError( msg = (
f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n"
f"Valid values are: {', '.join(speed_chart_inverse)}" f"Valid values are: {', '.join(speed_chart_inverse)}"
) )
raise ValueError(msg)
return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3)

View File

@ -299,10 +299,11 @@ def weight_conversion(from_type: str, to_type: str, value: float) -> float:
1.999999998903455 1.999999998903455
""" """
if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART: if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART:
raise ValueError( msg = (
f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"
f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}" f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}"
) )
raise ValueError(msg)
return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type] return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type]

View File

@ -77,7 +77,8 @@ class BinarySearchTree:
elif label > node.label: elif label > node.label:
node.right = self._put(node.right, label, node) node.right = self._put(node.right, label, node)
else: else:
raise Exception(f"Node with label {label} already exists") msg = f"Node with label {label} already exists"
raise Exception(msg)
return node return node
@ -100,7 +101,8 @@ class BinarySearchTree:
def _search(self, node: Node | None, label: int) -> Node: def _search(self, node: Node | None, label: int) -> Node:
if node is None: if node is None:
raise Exception(f"Node with label {label} does not exist") msg = f"Node with label {label} does not exist"
raise Exception(msg)
else: else:
if label < node.label: if label < node.label:
node = self._search(node.left, label) node = self._search(node.left, label)

View File

@ -31,7 +31,8 @@ def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict:
if not binary_tree: if not binary_tree:
raise ValueError("binary tree cannot be empty") raise ValueError("binary tree cannot be empty")
if root not in binary_tree: if root not in binary_tree:
raise ValueError(f"root {root} is not present in the binary_tree") msg = f"root {root} is not present in the binary_tree"
raise ValueError(msg)
binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dictionary = dict(binary_tree)
binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root)
return binary_tree_mirror_dictionary return binary_tree_mirror_dictionary

View File

@ -56,7 +56,8 @@ def find_python_set(node: Node) -> set:
for s in sets: for s in sets:
if node.data in s: if node.data in s:
return s return s
raise ValueError(f"{node.data} is not in {sets}") msg = f"{node.data} is not in {sets}"
raise ValueError(msg)
def test_disjoint_set() -> None: def test_disjoint_set() -> None:

View File

@ -94,25 +94,25 @@ def test_circular_linked_list() -> None:
try: try:
circular_linked_list.delete_front() circular_linked_list.delete_front()
raise AssertionError() # This should not happen raise AssertionError # This should not happen
except IndexError: except IndexError:
assert True # This should happen assert True # This should happen
try: try:
circular_linked_list.delete_tail() circular_linked_list.delete_tail()
raise AssertionError() # This should not happen raise AssertionError # This should not happen
except IndexError: except IndexError:
assert True # This should happen assert True # This should happen
try: try:
circular_linked_list.delete_nth(-1) circular_linked_list.delete_nth(-1)
raise AssertionError() raise AssertionError
except IndexError: except IndexError:
assert True assert True
try: try:
circular_linked_list.delete_nth(0) circular_linked_list.delete_nth(0)
raise AssertionError() raise AssertionError
except IndexError: except IndexError:
assert True assert True

View File

@ -198,13 +198,13 @@ def test_doubly_linked_list() -> None:
try: try:
linked_list.delete_head() linked_list.delete_head()
raise AssertionError() # This should not happen. raise AssertionError # This should not happen.
except IndexError: except IndexError:
assert True # This should happen. assert True # This should happen.
try: try:
linked_list.delete_tail() linked_list.delete_tail()
raise AssertionError() # This should not happen. raise AssertionError # This should not happen.
except IndexError: except IndexError:
assert True # This should happen. assert True # This should happen.

View File

@ -353,13 +353,13 @@ def test_singly_linked_list() -> None:
try: try:
linked_list.delete_head() linked_list.delete_head()
raise AssertionError() # This should not happen. raise AssertionError # This should not happen.
except IndexError: except IndexError:
assert True # This should happen. assert True # This should happen.
try: try:
linked_list.delete_tail() linked_list.delete_tail()
raise AssertionError() # This should not happen. raise AssertionError # This should not happen.
except IndexError: except IndexError:
assert True # This should happen. assert True # This should happen.

View File

@ -92,13 +92,13 @@ def test_stack() -> None:
try: try:
_ = stack.pop() _ = stack.pop()
raise AssertionError() # This should not happen raise AssertionError # This should not happen
except StackUnderflowError: except StackUnderflowError:
assert True # This should happen assert True # This should happen
try: try:
_ = stack.peek() _ = stack.peek()
raise AssertionError() # This should not happen raise AssertionError # This should not happen
except StackUnderflowError: except StackUnderflowError:
assert True # This should happen assert True # This should happen
@ -118,7 +118,7 @@ def test_stack() -> None:
try: try:
stack.push(200) stack.push(200)
raise AssertionError() # This should not happen raise AssertionError # This should not happen
except StackOverflowError: except StackOverflowError:
assert True # This should happen assert True # This should happen

View File

@ -21,7 +21,8 @@ class Burkes:
self.max_threshold = int(self.get_greyscale(255, 255, 255)) self.max_threshold = int(self.get_greyscale(255, 255, 255))
if not self.min_threshold < threshold < self.max_threshold: if not self.min_threshold < threshold < self.max_threshold:
raise ValueError(f"Factor value should be from 0 to {self.max_threshold}") msg = f"Factor value should be from 0 to {self.max_threshold}"
raise ValueError(msg)
self.input_img = input_img self.input_img = input_img
self.threshold = threshold self.threshold = threshold

View File

@ -174,12 +174,12 @@ def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]:
""" """
if not hasattr(points, "__iter__"): if not hasattr(points, "__iter__"):
raise ValueError( msg = f"Expecting an iterable object but got an non-iterable type {points}"
f"Expecting an iterable object but got an non-iterable type {points}" raise ValueError(msg)
)
if not points: if not points:
raise ValueError(f"Expecting a list of points but got {points}") msg = f"Expecting a list of points but got {points}"
raise ValueError(msg)
return _construct_points(points) return _construct_points(points)

View File

@ -78,17 +78,18 @@ def knapsack_with_example_solution(w: int, wt: list, val: list):
num_items = len(wt) num_items = len(wt)
if num_items != len(val): if num_items != len(val):
raise ValueError( msg = (
"The number of weights must be the " "The number of weights must be the same as the number of values.\n"
"same as the number of values.\nBut " f"But got {num_items} weights and {len(val)} values"
f"got {num_items} weights and {len(val)} values"
) )
raise ValueError(msg)
for i in range(num_items): for i in range(num_items):
if not isinstance(wt[i], int): if not isinstance(wt[i], int):
raise TypeError( msg = (
"All weights must be integers but " "All weights must be integers but got weight of "
f"got weight of type {type(wt[i])} at index {i}" f"type {type(wt[i])} at index {i}"
) )
raise TypeError(msg)
optimal_val, dp_table = knapsack(w, wt, val, num_items) optimal_val, dp_table = knapsack(w, wt, val, num_items)
example_optional_set: set = set() example_optional_set: set = set()

View File

@ -42,7 +42,8 @@ def min_steps_to_one(number: int) -> int:
""" """
if number <= 0: if number <= 0:
raise ValueError(f"n must be greater than 0. Got n = {number}") msg = f"n must be greater than 0. Got n = {number}"
raise ValueError(msg)
table = [number + 1] * (number + 1) table = [number + 1] * (number + 1)

View File

@ -177,13 +177,15 @@ def _enforce_args(n: int, prices: list):
the rod the rod
""" """
if n < 0: if n < 0:
raise ValueError(f"n must be greater than or equal to 0. Got n = {n}") msg = f"n must be greater than or equal to 0. Got n = {n}"
raise ValueError(msg)
if n > len(prices): if n > len(prices):
raise ValueError( msg = (
"Each integral piece of rod must have a corresponding " "Each integral piece of rod must have a corresponding price. "
f"price. Got n = {n} but length of prices = {len(prices)}" f"Got n = {n} but length of prices = {len(prices)}"
) )
raise ValueError(msg)
def main(): def main():

View File

@ -297,11 +297,13 @@ def _validate_list(_object: Any, var_name: str) -> None:
""" """
if not isinstance(_object, list): if not isinstance(_object, list):
raise ValueError(f"{var_name} must be a list") msg = f"{var_name} must be a list"
raise ValueError(msg)
else: else:
for x in _object: for x in _object:
if not isinstance(x, str): if not isinstance(x, str):
raise ValueError(f"{var_name} must be a list of strings") msg = f"{var_name} must be a list of strings"
raise ValueError(msg)
def _validate_dicts( def _validate_dicts(
@ -384,14 +386,15 @@ def _validate_dict(
ValueError: mock_name nested dictionary all values must be float ValueError: mock_name nested dictionary all values must be float
""" """
if not isinstance(_object, dict): if not isinstance(_object, dict):
raise ValueError(f"{var_name} must be a dict") msg = f"{var_name} must be a dict"
raise ValueError(msg)
if not all(isinstance(x, str) for x in _object): if not all(isinstance(x, str) for x in _object):
raise ValueError(f"{var_name} all keys must be strings") msg = f"{var_name} all keys must be strings"
raise ValueError(msg)
if not all(isinstance(x, value_type) for x in _object.values()): if not all(isinstance(x, value_type) for x in _object.values()):
nested_text = "nested dictionary " if nested else "" nested_text = "nested dictionary " if nested else ""
raise ValueError( msg = f"{var_name} {nested_text}all values must be {value_type.__name__}"
f"{var_name} {nested_text}all values must be {value_type.__name__}" raise ValueError(msg)
)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -23,7 +23,8 @@ def resistor_parallel(resistors: list[float]) -> float:
index = 0 index = 0
for resistor in resistors: for resistor in resistors:
if resistor <= 0: if resistor <= 0:
raise ValueError(f"Resistor at index {index} has a negative or zero value!") msg = f"Resistor at index {index} has a negative or zero value!"
raise ValueError(msg)
first_sum += 1 / float(resistor) first_sum += 1 / float(resistor)
index += 1 index += 1
return 1 / first_sum return 1 / first_sum
@ -47,7 +48,8 @@ def resistor_series(resistors: list[float]) -> float:
for resistor in resistors: for resistor in resistors:
sum_r += resistor sum_r += resistor
if resistor < 0: if resistor < 0:
raise ValueError(f"Resistor at index {index} has a negative value!") msg = f"Resistor at index {index} has a negative value!"
raise ValueError(msg)
index += 1 index += 1
return sum_r return sum_r

View File

@ -96,13 +96,13 @@ def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int,
# Verify if N_POPULATION is bigger than N_SELECTED # Verify if N_POPULATION is bigger than N_SELECTED
if N_POPULATION < N_SELECTED: if N_POPULATION < N_SELECTED:
raise ValueError(f"{N_POPULATION} must be bigger than {N_SELECTED}") msg = f"{N_POPULATION} must be bigger than {N_SELECTED}"
raise ValueError(msg)
# Verify that the target contains no genes besides the ones inside genes variable. # Verify that the target contains no genes besides the ones inside genes variable.
not_in_genes_list = sorted({c for c in target if c not in genes}) not_in_genes_list = sorted({c for c in target if c not in genes})
if not_in_genes_list: if not_in_genes_list:
raise ValueError( msg = f"{not_in_genes_list} is not in genes list, evolution cannot converge"
f"{not_in_genes_list} is not in genes list, evolution cannot converge" raise ValueError(msg)
)
# Generate random starting population. # Generate random starting population.
population = [] population = []

View File

@ -28,9 +28,8 @@ def convert_to_2d(
TypeError: Input values must either be float or int: ['1', 2, 3, 10, 10] TypeError: Input values must either be float or int: ['1', 2, 3, 10, 10]
""" """
if not all(isinstance(val, (float, int)) for val in locals().values()): if not all(isinstance(val, (float, int)) for val in locals().values()):
raise TypeError( msg = f"Input values must either be float or int: {list(locals().values())}"
"Input values must either be float or int: " f"{list(locals().values())}" raise TypeError(msg)
)
projected_x = ((x * distance) / (z + distance)) * scale projected_x = ((x * distance) / (z + distance)) * scale
projected_y = ((y * distance) / (z + distance)) * scale projected_y = ((y * distance) / (z + distance)) * scale
return projected_x, projected_y return projected_x, projected_y
@ -71,10 +70,11 @@ def rotate(
input_variables = locals() input_variables = locals()
del input_variables["axis"] del input_variables["axis"]
if not all(isinstance(val, (float, int)) for val in input_variables.values()): if not all(isinstance(val, (float, int)) for val in input_variables.values()):
raise TypeError( msg = (
"Input values except axis must either be float or int: " "Input values except axis must either be float or int: "
f"{list(input_variables.values())}" f"{list(input_variables.values())}"
) )
raise TypeError(msg)
angle = (angle % 360) / 450 * 180 / math.pi angle = (angle % 360) / 450 * 180 / math.pi
if axis == "z": if axis == "z":
new_x = x * math.cos(angle) - y * math.sin(angle) new_x = x * math.cos(angle) - y * math.sin(angle)

View File

@ -73,9 +73,10 @@ class Graph:
target_vertex_parent = self.parent.get(target_vertex) target_vertex_parent = self.parent.get(target_vertex)
if target_vertex_parent is None: if target_vertex_parent is None:
raise ValueError( msg = (
f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}"
) )
raise ValueError(msg)
return self.shortest_path(target_vertex_parent) + f"->{target_vertex}" return self.shortest_path(target_vertex_parent) + f"->{target_vertex}"

View File

@ -31,16 +31,18 @@ def schur_complement(
shape_c = np.shape(mat_c) shape_c = np.shape(mat_c)
if shape_a[0] != shape_b[0]: if shape_a[0] != shape_b[0]:
raise ValueError( msg = (
f"Expected the same number of rows for A and B. \ "Expected the same number of rows for A and B. "
Instead found A of size {shape_a} and B of size {shape_b}" f"Instead found A of size {shape_a} and B of size {shape_b}"
) )
raise ValueError(msg)
if shape_b[1] != shape_c[1]: if shape_b[1] != shape_c[1]:
raise ValueError( msg = (
f"Expected the same number of columns for B and C. \ "Expected the same number of columns for B and C. "
Instead found B of size {shape_b} and C of size {shape_c}" f"Instead found B of size {shape_b} and C of size {shape_c}"
) )
raise ValueError(msg)
a_inv = pseudo_inv a_inv = pseudo_inv
if a_inv is None: if a_inv is None:

View File

@ -97,26 +97,29 @@ def similarity_search(
""" """
if dataset.ndim != value_array.ndim: if dataset.ndim != value_array.ndim:
raise ValueError( msg = (
f"Wrong input data's dimensions... dataset : {dataset.ndim}, " "Wrong input data's dimensions... "
f"value_array : {value_array.ndim}" f"dataset : {dataset.ndim}, value_array : {value_array.ndim}"
) )
raise ValueError(msg)
try: try:
if dataset.shape[1] != value_array.shape[1]: if dataset.shape[1] != value_array.shape[1]:
raise ValueError( msg = (
f"Wrong input data's shape... dataset : {dataset.shape[1]}, " "Wrong input data's shape... "
f"value_array : {value_array.shape[1]}" f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}"
) )
raise ValueError(msg)
except IndexError: except IndexError:
if dataset.ndim != value_array.ndim: if dataset.ndim != value_array.ndim:
raise TypeError("Wrong shape") raise TypeError("Wrong shape")
if dataset.dtype != value_array.dtype: if dataset.dtype != value_array.dtype:
raise TypeError( msg = (
f"Input data have different datatype... dataset : {dataset.dtype}, " "Input data have different datatype... "
f"value_array : {value_array.dtype}" f"dataset : {dataset.dtype}, value_array : {value_array.dtype}"
) )
raise TypeError(msg)
answer = [] answer = []

View File

@ -74,7 +74,8 @@ class SVC:
# sklear: def_gamma = 1/(n_features * X.var()) (wiki) # sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features) # previously it was 1/(n_features)
else: else:
raise ValueError(f"Unknown kernel: {kernel}") msg = f"Unknown kernel: {kernel}"
raise ValueError(msg)
# kernels # kernels
def __linear(self, vector1: ndarray, vector2: ndarray) -> float: def __linear(self, vector1: ndarray, vector2: ndarray) -> float:

View File

@ -9,9 +9,11 @@ def n31(a: int) -> tuple[list[int], int]:
""" """
if not isinstance(a, int): if not isinstance(a, int):
raise TypeError(f"Must be int, not {type(a).__name__}") msg = f"Must be int, not {type(a).__name__}"
raise TypeError(msg)
if a < 1: if a < 1:
raise ValueError(f"Given integer must be positive, not {a}") msg = f"Given integer must be positive, not {a}"
raise ValueError(msg)
path = [a] path = [a]
while a != 1: while a != 1:

View File

@ -40,7 +40,8 @@ def is_automorphic_number(number: int) -> bool:
TypeError: Input value of [number=5.0] must be an integer TypeError: Input value of [number=5.0] must be an integer
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer") msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 0: if number < 0:
return False return False
number_square = number * number number_square = number * number

View File

@ -31,10 +31,12 @@ def catalan(number: int) -> int:
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer") msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 1: if number < 1:
raise ValueError(f"Input value of [number={number}] must be > 0") msg = f"Input value of [number={number}] must be > 0"
raise ValueError(msg)
current_number = 1 current_number = 1

View File

@ -71,7 +71,7 @@ class Dual:
for i in self.duals: for i in self.duals:
new_duals.append(i / other) new_duals.append(i / other)
return Dual(self.real / other, new_duals) return Dual(self.real / other, new_duals)
raise ValueError() raise ValueError
def __floordiv__(self, other): def __floordiv__(self, other):
if not isinstance(other, Dual): if not isinstance(other, Dual):
@ -79,7 +79,7 @@ class Dual:
for i in self.duals: for i in self.duals:
new_duals.append(i // other) new_duals.append(i // other)
return Dual(self.real // other, new_duals) return Dual(self.real // other, new_duals)
raise ValueError() raise ValueError
def __pow__(self, n): def __pow__(self, n):
if n < 0 or isinstance(n, float): if n < 0 or isinstance(n, float):

View File

@ -36,7 +36,8 @@ def hexagonal(number: int) -> int:
TypeError: Input value of [number=11.0] must be an integer TypeError: Input value of [number=11.0] must be an integer
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer") msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 1: if number < 1:
raise ValueError("Input must be a positive integer") raise ValueError("Input must be a positive integer")
return number * (2 * number - 1) return number * (2 * number - 1)

View File

@ -40,9 +40,11 @@ def juggler_sequence(number: int) -> list[int]:
ValueError: Input value of [number=-1] must be a positive integer ValueError: Input value of [number=-1] must be a positive integer
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer") msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 1: if number < 1:
raise ValueError(f"Input value of [number={number}] must be a positive integer") msg = f"Input value of [number={number}] must be a positive integer"
raise ValueError(msg)
sequence = [number] sequence = [number]
while number != 1: while number != 1:
if number % 2 == 0: if number % 2 == 0:

View File

@ -33,7 +33,8 @@ def liouville_lambda(number: int) -> int:
TypeError: Input value of [number=11.0] must be an integer TypeError: Input value of [number=11.0] must be an integer
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer") msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 1: if number < 1:
raise ValueError("Input must be a positive integer") raise ValueError("Input must be a positive integer")
return -1 if len(prime_factors(number)) % 2 else 1 return -1 if len(prime_factors(number)) % 2 else 1

View File

@ -66,14 +66,14 @@ def _validate_point(point: list[float]) -> None:
if isinstance(point, list): if isinstance(point, list):
for item in point: for item in point:
if not isinstance(item, (int, float)): if not isinstance(item, (int, float)):
raise TypeError( msg = (
f"Expected a list of numbers as input, " "Expected a list of numbers as input, found "
f"found {type(item).__name__}" f"{type(item).__name__}"
) )
raise TypeError(msg)
else: else:
raise TypeError( msg = f"Expected a list of numbers as input, found {type(point).__name__}"
f"Expected a list of numbers as input, found {type(point).__name__}" raise TypeError(msg)
)
else: else:
raise ValueError("Missing an input") raise ValueError("Missing an input")

View File

@ -41,7 +41,8 @@ def is_pronic(number: int) -> bool:
TypeError: Input value of [number=6.0] must be an integer TypeError: Input value of [number=6.0] must be an integer
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer") msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 0 or number % 2 == 1: if number < 0 or number % 2 == 1:
return False return False
number_sqrt = int(number**0.5) number_sqrt = int(number**0.5)

View File

@ -29,10 +29,12 @@ def proth(number: int) -> int:
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer") msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 1: if number < 1:
raise ValueError(f"Input value of [number={number}] must be > 0") msg = f"Input value of [number={number}] must be > 0"
raise ValueError(msg)
elif number == 1: elif number == 1:
return 3 return 3
elif number == 2: elif number == 2:

View File

@ -167,7 +167,7 @@ class FFT:
f"{coef}*x^{i}" for coef, i in enumerate(self.product) f"{coef}*x^{i}" for coef, i in enumerate(self.product)
) )
return "\n".join((a, b, c)) return f"{a}\n{b}\n{c}"
# Unit tests # Unit tests

View File

@ -34,7 +34,8 @@ def prime_sieve(num: int) -> list[int]:
""" """
if num <= 0: if num <= 0:
raise ValueError(f"{num}: Invalid input, please enter a positive integer.") msg = f"{num}: Invalid input, please enter a positive integer."
raise ValueError(msg)
sieve = [True] * (num + 1) sieve = [True] * (num + 1)
prime = [] prime = []

View File

@ -31,7 +31,8 @@ def sylvester(number: int) -> int:
if number == 1: if number == 1:
return 2 return 2
elif number < 1: elif number < 1:
raise ValueError(f"The input value of [n={number}] has to be > 0") msg = f"The input value of [n={number}] has to be > 0"
raise ValueError(msg)
else: else:
num = sylvester(number - 1) num = sylvester(number - 1)
lower = num - 1 lower = num - 1

View File

@ -32,7 +32,8 @@ def twin_prime(number: int) -> int:
TypeError: Input value of [number=6.0] must be an integer TypeError: Input value of [number=6.0] must be an integer
""" """
if not isinstance(number, int): if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer") msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if is_prime(number) and is_prime(number + 2): if is_prime(number) and is_prime(number + 2):
return number + 2 return number + 2
else: else:

View File

@ -70,10 +70,11 @@ def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[
rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)
if cols[0] != rows[1]: if cols[0] != rows[1]:
raise ValueError( msg = (
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) " "Cannot multiply matrix of dimensions "
f"and ({rows[1]},{cols[1]})" f"({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})"
) )
raise ValueError(msg)
return [ return [
[sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a [sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a
] ]
@ -174,10 +175,11 @@ def _verify_matrix_sizes(
) -> tuple[tuple[int, int], tuple[int, int]]: ) -> tuple[tuple[int, int], tuple[int, int]]:
shape = _shape(matrix_a) + _shape(matrix_b) shape = _shape(matrix_a) + _shape(matrix_b)
if shape[0] != shape[3] or shape[1] != shape[2]: if shape[0] != shape[3] or shape[1] != shape[2]:
raise ValueError( msg = (
f"operands could not be broadcast together with shape " "operands could not be broadcast together with shape "
f"({shape[0], shape[1]}), ({shape[2], shape[3]})" f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
) )
raise ValueError(msg)
return (shape[0], shape[2]), (shape[1], shape[3]) return (shape[0], shape[2]), (shape[1], shape[3])

View File

@ -173,7 +173,8 @@ class Matrix:
result[r, c] += self[r, i] * another[i, c] result[r, c] += self[r, i] * another[i, c]
return result return result
else: else:
raise TypeError(f"Unsupported type given for another ({type(another)})") msg = f"Unsupported type given for another ({type(another)})"
raise TypeError(msg)
def transpose(self) -> Matrix: def transpose(self) -> Matrix:
""" """

View File

@ -198,10 +198,7 @@ class _DataSet:
"""Return the next `batch_size` examples from this data set.""" """Return the next `batch_size` examples from this data set."""
if fake_data: if fake_data:
fake_image = [1] * 784 fake_image = [1] * 784
if self.one_hot: fake_label = [1] + [0] * 9 if self.one_hot else 0
fake_label = [1] + [0] * 9
else:
fake_label = 0
return ( return (
[fake_image for _ in range(batch_size)], [fake_image for _ in range(batch_size)],
[fake_label for _ in range(batch_size)], [fake_label for _ in range(batch_size)],
@ -324,10 +321,11 @@ def read_data_sets(
test_labels = _extract_labels(f, one_hot=one_hot) test_labels = _extract_labels(f, one_hot=one_hot)
if not 0 <= validation_size <= len(train_images): if not 0 <= validation_size <= len(train_images):
raise ValueError( msg = (
f"Validation size should be between 0 and {len(train_images)}. " "Validation size should be between 0 and "
f"Received: {validation_size}." f"{len(train_images)}. Received: {validation_size}."
) )
raise ValueError(msg)
validation_images = train_images[:validation_size] validation_images = train_images[:validation_size]
validation_labels = train_labels[:validation_size] validation_labels = train_labels[:validation_size]

View File

@ -18,7 +18,7 @@ def is_balanced(s):
stack = [] stack = []
open_brackets = set({"(", "[", "{"}) open_brackets = set({"(", "[", "{"})
closed_brackets = set({")", "]", "}"}) closed_brackets = set({")", "]", "}"})
open_to_closed = dict({"{": "}", "[": "]", "(": ")"}) open_to_closed = {"{": "}", "[": "]", "(": ")"}
for i in range(len(s)): for i in range(len(s)):
if s[i] in open_brackets: if s[i] in open_brackets:

View File

@ -68,7 +68,8 @@ def calculate_each_score(
# weight not 0 or 1 # weight not 0 or 1
else: else:
raise ValueError(f"Invalid weight of {weight:f} provided") msg = f"Invalid weight of {weight:f} provided"
raise ValueError(msg)
score_lists.append(score) score_lists.append(score)

View File

@ -119,10 +119,12 @@ class PokerHand:
For example: "6S 4C KC AS TH" For example: "6S 4C KC AS TH"
""" """
if not isinstance(hand, str): if not isinstance(hand, str):
raise TypeError(f"Hand should be of type 'str': {hand!r}") msg = f"Hand should be of type 'str': {hand!r}"
raise TypeError(msg)
# split removes duplicate whitespaces so no need of strip # split removes duplicate whitespaces so no need of strip
if len(hand.split(" ")) != 5: if len(hand.split(" ")) != 5:
raise ValueError(f"Hand should contain only 5 cards: {hand!r}") msg = f"Hand should contain only 5 cards: {hand!r}"
raise ValueError(msg)
self._hand = hand self._hand = hand
self._first_pair = 0 self._first_pair = 0
self._second_pair = 0 self._second_pair = 0

View File

@ -73,7 +73,8 @@ def solution(gon_side: int = 5) -> int:
if is_magic_gon(numbers): if is_magic_gon(numbers):
return int("".join(str(n) for n in numbers)) return int("".join(str(n) for n in numbers))
raise ValueError(f"Magic {gon_side}-gon ring is impossible") msg = f"Magic {gon_side}-gon ring is impossible"
raise ValueError(msg)
def generate_gon_ring(gon_side: int, perm: list[int]) -> list[int]: def generate_gon_ring(gon_side: int, perm: list[int]) -> list[int]:

View File

@ -26,10 +26,7 @@ def is_prime(number: int) -> bool:
False False
""" """
for divisor in range(2, isqrt(number) + 1): return all(number % divisor != 0 for divisor in range(2, isqrt(number) + 1))
if number % divisor == 0:
return False
return True
def solution(max_prime: int = 10**6) -> int: def solution(max_prime: int = 10**6) -> int:

View File

@ -18,44 +18,87 @@ skip = "./.*,*.json,ciphers/prehistoric_men.txt,project_euler/problem_022/p022_n
[tool.ruff] [tool.ruff]
ignore = [ # `ruff rule S101` for a description of that rule ignore = [ # `ruff rule S101` for a description of that rule
"B904", # B904: Within an `except` clause, raise exceptions with `raise ... from err` "ARG001", # Unused function argument `amount` -- FIX ME?
"B905", # B905: `zip()` without an explicit `strict=` parameter "B904", # Within an `except` clause, raise exceptions with `raise ... from err` -- FIX ME
"E741", # E741: Ambiguous variable name 'l' "B905", # `zip()` without an explicit `strict=` parameter -- FIX ME
"G004", # G004 Logging statement uses f-string "DTZ001", # The use of `datetime.datetime()` without `tzinfo` argument is not allowed -- FIX ME
"N999", # N999: Invalid module name "DTZ005", # The use of `datetime.datetime.now()` without `tzinfo` argument is not allowed -- FIX ME
"PLC1901", # PLC1901: `{}` can be simplified to `{}` as an empty string is falsey "E741", # Ambiguous variable name 'l' -- FIX ME
"PLR2004", # PLR2004: Magic value used in comparison "EM101", # Exception must not use a string literal, assign to variable first
"PLR5501", # PLR5501: Consider using `elif` instead of `else` "EXE001", # Shebang is present but file is not executable" -- FIX ME
"PLW0120", # PLW0120: `else` clause on loop without a `break` statement "G004", # Logging statement uses f-string
"PLW060", # PLW060: Using global for `{name}` but no assignment is done -- DO NOT FIX "ICN001", # `matplotlib.pyplot` should be imported as `plt` -- FIX ME
"PLW2901", # PLW2901: Redefined loop variable "INP001", # File `x/y/z.py` is part of an implicit namespace package. Add an `__init__.py`. -- FIX ME
"RUF00", # RUF00: Ambiguous unicode character -- DO NOT FIX "N999", # Invalid module name -- FIX ME
"RUF100", # RUF100: Unused `noqa` directive "NPY002", # Replace legacy `np.random.choice` call with `np.random.Generator` -- FIX ME
"S101", # S101: Use of `assert` detected -- DO NOT FIX "PGH003", # Use specific rule codes when ignoring type issues -- FIX ME
"S105", # S105: Possible hardcoded password: 'password' "PLC1901", # `{}` can be simplified to `{}` as an empty string is falsey
"S113", # S113: Probable use of requests call without timeout "PLR5501", # Consider using `elif` instead of `else` -- FIX ME
"S311", # S311: Standard pseudo-random generators are not suitable for cryptographic purposes "PLW0120", # `else` clause on loop without a `break` statement -- FIX ME
"UP038", # UP038: Use `X | Y` in `{}` call instead of `(X, Y)` -- DO NOT FIX "PLW060", # Using global for `{name}` but no assignment is done -- DO NOT FIX
"PLW2901", # PLW2901: Redefined loop variable -- FIX ME
"RUF00", # Ambiguous unicode character and other rules
"RUF100", # Unused `noqa` directive -- FIX ME
"S101", # Use of `assert` detected -- DO NOT FIX
"S105", # Possible hardcoded password: 'password'
"S113", # Probable use of requests call without timeout -- FIX ME
"S311", # Standard pseudo-random generators are not suitable for cryptographic purposes -- FIX ME
"SIM102", # Use a single `if` statement instead of nested `if` statements -- FIX ME
"SLF001", # Private member accessed: `_Iterator` -- FIX ME
"UP038", # Use `X | Y` in `{}` call instead of `(X, Y)` -- DO NOT FIX
] ]
select = [ # https://beta.ruff.rs/docs/rules select = [ # https://beta.ruff.rs/docs/rules
"A", # A: builtins "A", # flake8-builtins
"B", # B: bugbear "ARG", # flake8-unused-arguments
"C40", # C40: comprehensions "ASYNC", # flake8-async
"C90", # C90: mccabe code complexity "B", # flake8-bugbear
"E", # E: pycodestyle errors "BLE", # flake8-blind-except
"F", # F: pyflakes "C4", # flake8-comprehensions
"G", # G: logging format "C90", # McCabe cyclomatic complexity
"I", # I: isort "DTZ", # flake8-datetimez
"N", # N: pep8 naming "E", # pycodestyle
"PL", # PL: pylint "EM", # flake8-errmsg
"PIE", # PIE: pie "EXE", # flake8-executable
"PYI", # PYI: type hinting stub files "F", # Pyflakes
"RUF", # RUF: ruff "FA", # flake8-future-annotations
"S", # S: bandit "FLY", # flynt
"TID", # TID: tidy imports "G", # flake8-logging-format
"UP", # UP: pyupgrade "I", # isort
"W", # W: pycodestyle warnings "ICN", # flake8-import-conventions
"YTT", # YTT: year 2020 "INP", # flake8-no-pep420
"INT", # flake8-gettext
"N", # pep8-naming
"NPY", # NumPy-specific rules
"PGH", # pygrep-hooks
"PIE", # flake8-pie
"PL", # Pylint
"PYI", # flake8-pyi
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"S", # flake8-bandit
"SIM", # flake8-simplify
"SLF", # flake8-self
"T10", # flake8-debugger
"TD", # flake8-todos
"TID", # flake8-tidy-imports
"UP", # pyupgrade
"W", # pycodestyle
"YTT", # flake8-2020
# "ANN", # flake8-annotations # FIX ME?
# "COM", # flake8-commas
# "D", # pydocstyle -- FIX ME?
# "DJ", # flake8-django
# "ERA", # eradicate -- DO NOT FIX
# "FBT", # flake8-boolean-trap # FIX ME
# "ISC", # flake8-implicit-str-concat # FIX ME
# "PD", # pandas-vet
# "PT", # flake8-pytest-style
# "PTH", # flake8-use-pathlib # FIX ME
# "Q", # flake8-quotes
# "RET", # flake8-return # FIX ME?
# "T20", # flake8-print
# "TCH", # flake8-type-checking
# "TRY", # tryceratops
] ]
show-source = true show-source = true
target-version = "py311" target-version = "py311"
@ -63,7 +106,27 @@ target-version = "py311"
[tool.ruff.mccabe] # DO NOT INCREASE THIS VALUE [tool.ruff.mccabe] # DO NOT INCREASE THIS VALUE
max-complexity = 17 # default: 10 max-complexity = 17 # default: 10
[tool.ruff.per-file-ignores]
"arithmetic_analysis/newton_raphson.py" = ["PGH001"]
"audio_filters/show_response.py" = ["ARG002"]
"data_structures/binary_tree/binary_search_tree_recursive.py" = ["BLE001"]
"data_structures/binary_tree/treap.py" = ["SIM114"]
"data_structures/hashing/hash_table.py" = ["ARG002"]
"data_structures/hashing/quadratic_probing.py" = ["ARG002"]
"data_structures/hashing/tests/test_hash_map.py" = ["BLE001"]
"data_structures/heap/max_heap.py" = ["SIM114"]
"graphs/minimum_spanning_tree_prims.py" = ["SIM114"]
"hashes/enigma_machine.py" = ["BLE001"]
"machine_learning/decision_tree.py" = ["SIM114"]
"machine_learning/linear_discriminant_analysis.py" = ["ARG005"]
"machine_learning/sequential_minimum_optimization.py" = ["SIM115"]
"matrix/sherman_morrison.py" = ["SIM103", "SIM114"]
"physics/newtons_second_law_of_motion.py" = ["BLE001"]
"project_euler/problem_099/sol1.py" = ["SIM115"]
"sorts/external_sort.py" = ["SIM115"]
[tool.ruff.pylint] # DO NOT INCREASE THESE VALUES [tool.ruff.pylint] # DO NOT INCREASE THESE VALUES
allow-magic-value-types = ["float", "int", "str"]
max-args = 10 # default: 5 max-args = 10 # default: 5
max-branches = 20 # default: 12 max-branches = 20 # default: 12
max-returns = 8 # default: 6 max-returns = 8 # default: 6

View File

@ -33,7 +33,7 @@ def print_directory_md(top_dir: str = ".") -> None:
if filepath != old_path: if filepath != old_path:
old_path = print_path(old_path, filepath) old_path = print_path(old_path, filepath)
indent = (filepath.count(os.sep) + 1) if filepath else 0 indent = (filepath.count(os.sep) + 1) if filepath else 0
url = "/".join((filepath, filename)).replace(" ", "%20") url = f"{filepath}/{filename}".replace(" ", "%20")
filename = os.path.splitext(filename.replace("_", " ").title())[0] filename = os.path.splitext(filename.replace("_", " ").title())[0]
print(f"{md_prefix(indent)} [{filename}]({url})") print(f"{md_prefix(indent)} [{filename}]({url})")

View File

@ -84,9 +84,8 @@ def dutch_national_flag_sort(sequence: list) -> list:
sequence[mid], sequence[high] = sequence[high], sequence[mid] sequence[mid], sequence[high] = sequence[high], sequence[mid]
high -= 1 high -= 1
else: else:
raise ValueError( msg = f"The elements inside the sequence must contains only {colors} values"
f"The elements inside the sequence must contains only {colors} values" raise ValueError(msg)
)
return sequence return sequence

View File

@ -65,7 +65,8 @@ def get_barcode(barcode: str) -> int:
ValueError: Barcode 'dwefgiweuf' has alphabetic characters. ValueError: Barcode 'dwefgiweuf' has alphabetic characters.
""" """
if str(barcode).isalpha(): if str(barcode).isalpha():
raise ValueError(f"Barcode '{barcode}' has alphabetic characters.") msg = f"Barcode '{barcode}' has alphabetic characters."
raise ValueError(msg)
elif int(barcode) < 0: elif int(barcode) < 0:
raise ValueError("The entered barcode has a negative value. Try again.") raise ValueError("The entered barcode has a negative value. Try again.")
else: else:

View File

@ -17,7 +17,7 @@ def capitalize(sentence: str) -> str:
""" """
if not sentence: if not sentence:
return "" return ""
lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)} lower_to_upper = dict(zip(ascii_lowercase, ascii_uppercase))
return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:] return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:]

View File

@ -48,7 +48,8 @@ def is_spain_national_id(spanish_id: str) -> bool:
""" """
if not isinstance(spanish_id, str): if not isinstance(spanish_id, str):
raise TypeError(f"Expected string as input, found {type(spanish_id).__name__}") msg = f"Expected string as input, found {type(spanish_id).__name__}"
raise TypeError(msg)
spanish_id_clean = spanish_id.replace("-", "").upper() spanish_id_clean = spanish_id.replace("-", "").upper()
if len(spanish_id_clean) != 9: if len(spanish_id_clean) != 9:

View File

@ -27,11 +27,11 @@ def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str:
""" """
if not isinstance(input_str, str): if not isinstance(input_str, str):
raise ValueError(f"Expected string as input, found {type(input_str)}") msg = f"Expected string as input, found {type(input_str)}"
raise ValueError(msg)
if not isinstance(use_pascal, bool): if not isinstance(use_pascal, bool):
raise ValueError( msg = f"Expected boolean as use_pascal parameter, found {type(use_pascal)}"
f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" raise ValueError(msg)
)
words = input_str.split("_") words = input_str.split("_")

View File

@ -26,7 +26,8 @@ def get_subreddit_data(
""" """
wanted_data = wanted_data or [] wanted_data = wanted_data or []
if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)): if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)):
raise ValueError(f"Invalid search term: {invalid_search_terms}") msg = f"Invalid search term: {invalid_search_terms}"
raise ValueError(msg)
response = requests.get( response = requests.get(
f"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}", f"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}",
headers={"User-agent": "A random string"}, headers={"User-agent": "A random string"},

View File

@ -22,7 +22,8 @@ def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict:
""" """
new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes
if new_olid.count("/") != 1: if new_olid.count("/") != 1:
raise ValueError(f"{olid} is not a valid Open Library olid") msg = f"{olid} is not a valid Open Library olid"
raise ValueError(msg)
return requests.get(f"https://openlibrary.org/{new_olid}.json").json() return requests.get(f"https://openlibrary.org/{new_olid}.json").json()

View File

@ -7,10 +7,11 @@ def send_slack_message(message_body: str, slack_url: str) -> None:
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
response = requests.post(slack_url, json={"text": message_body}, headers=headers) response = requests.post(slack_url, json={"text": message_body}, headers=headers)
if response.status_code != 200: if response.status_code != 200:
raise ValueError( msg = (
f"Request to slack returned an error {response.status_code}, " "Request to slack returned an error "
f"the response is:\n{response.text}" f"{response.status_code}, the response is:\n{response.text}"
) )
raise ValueError(msg)
if __name__ == "__main__": if __name__ == "__main__":