Skip to content

fix graphs/greedy_best_first #8771

New issue

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

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

Already on GitHub? Sign in to your account

Closed
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.269
rev: v0.0.270
hooks:
- id: ruff

Expand Down
2 changes: 1 addition & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -577,8 +577,8 @@
* [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py)
* [Hexagonal Number](maths/hexagonal_number.py)
* [Integration By Simpson Approx](maths/integration_by_simpson_approx.py)
* [Is Int Palindrome](maths/is_int_palindrome.py)
* [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py)
* [Is Palindrome](maths/is_palindrome.py)
* [Is Square Free](maths/is_square_free.py)
* [Jaccard Similarity](maths/jaccard_similarity.py)
* [Juggler Sequence](maths/juggler_sequence.py)
Expand Down
30 changes: 18 additions & 12 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ def jacobi_iteration_method(
>>> constant = np.array([[2], [-6]])
>>> init_val = [0.5, -0.5, -0.5]
>>> 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):
...
ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but
Expand All @@ -59,7 +61,9 @@ def jacobi_iteration_method(
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5]
>>> 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):
...
ValueError: Number of initial values must be equal to number of rows in coefficient
Expand All @@ -79,24 +83,26 @@ def jacobi_iteration_method(
rows2, cols2 = constant_matrix.shape

if rows1 != cols1:
raise ValueError(
f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
)
msg = f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
raise ValueError(msg)

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:
raise ValueError(
f"""Coefficient and constant matrices dimensions must be nxn and nx1 but
received {rows1}x{cols1} and {rows2}x{cols2}"""
msg = (
"Coefficient and constant matrices dimensions must be nxn and nx1 but "
f"received {rows1}x{cols1} and {rows2}x{cols2}"
)
raise ValueError(msg)

if len(init_val) != rows1:
raise ValueError(
f"""Number of initial values must be equal to number of rows in coefficient
matrix but received {len(init_val)} and {rows1}"""
msg = (
"Number of initial values must be equal to number of rows in coefficient "
f"matrix but received {len(init_val)} and {rows1}"
)
raise ValueError(msg)

if iterations <= 0:
raise ValueError("Iterations must be at least 1")
Expand Down
5 changes: 3 additions & 2 deletions arithmetic_analysis/lu_decomposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,11 @@ def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray
# Ensure that table is a square array
rows, columns = np.shape(table)
if rows != columns:
raise ValueError(
f"'table' has to be of square shaped array but got a "
msg = (
"'table' has to be of square shaped array but got a "
f"{rows}x{columns} array:\n{table}"
)
raise ValueError(msg)

lower = np.zeros((rows, columns))
upper = np.zeros((rows, columns))
Expand Down
14 changes: 8 additions & 6 deletions audio_filters/iir_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,18 @@ def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None
a_coeffs = [1.0, *a_coeffs]

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

if len(b_coeffs) != self.order + 1:
raise ValueError(
f"Expected b_coeffs to have {self.order + 1} elements for {self.order}"
f"-order filter, got {len(a_coeffs)}"
msg = (
f"Expected b_coeffs to have {self.order + 1} elements "
f"for {self.order}-order filter, got {len(a_coeffs)}"
)
raise ValueError(msg)

self.a_coeffs = a_coeffs
self.b_coeffs = b_coeffs
Expand Down
3 changes: 2 additions & 1 deletion backtracking/knight_tour.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ def open_knight_tour(n: int) -> list[list[int]]:
return board
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__":
Expand Down
3 changes: 2 additions & 1 deletion bit_manipulation/reverse_bits.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ def get_reverse_bit_string(number: int) -> str:
TypeError: operation can not be conducted on a object of type str
"""
if not isinstance(number, int):
raise TypeError(
msg = (
"operation can not be conducted on a object of type "
f"{type(number).__name__}"
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
bit_string += str(number % 2)
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,8 @@ def base64_encode(data: bytes) -> bytes:
"""
# Make sure the supplied data is a bytes-like object
if not isinstance(data, bytes):
raise TypeError(
f"a bytes-like object is required, not '{data.__class__.__name__}'"
)
msg = 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)

Expand Down Expand Up @@ -88,10 +87,11 @@ def base64_decode(encoded_data: str) -> bytes:
"""
# 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):
raise TypeError(
"argument should be a bytes-like object or ASCII string, not "
f"'{encoded_data.__class__.__name__}'"
msg = (
"argument should be a bytes-like object or ASCII string, "
f"not '{encoded_data.__class__.__name__}'"
)
raise TypeError(msg)

# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
Expand Down
2 changes: 1 addition & 1 deletion ciphers/beaufort_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from string import 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
Expand Down
3 changes: 2 additions & 1 deletion ciphers/cryptomath_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ def gcd(a: int, b: int) -> int:

def find_mod_inverse(a: int, m: int) -> int:
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
v1, v2, v3 = 0, 1, m
while v3 != 0:
Expand Down
30 changes: 16 additions & 14 deletions ciphers/enigma_machine2.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,22 +87,20 @@ def _validator(
# Checks if there are 3 unique rotors

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
rotorpos1, rotorpos2, rotorpos3 = rotpos
if not 0 < rotorpos1 <= len(abc):
raise ValueError(
"First rotor position is not within range of 1..26 (" f"{rotorpos1}"
)
msg = f"First rotor position is not within range of 1..26 ({rotorpos1}"
raise ValueError(msg)
if not 0 < rotorpos2 <= len(abc):
raise ValueError(
"Second rotor position is not within range of 1..26 (" f"{rotorpos2})"
)
msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})"
raise ValueError(msg)
if not 0 < rotorpos3 <= len(abc):
raise ValueError(
"Third rotor position is not within range of 1..26 (" f"{rotorpos3})"
)
msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})"
raise ValueError(msg)

# Validates string and returns dict
pbdict = _plugboard(pb)
Expand Down Expand Up @@ -130,9 +128,11 @@ def _plugboard(pbstring: str) -> dict[str, str]:
# a) is type string
# b) has even length (so pairs can be made)
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:
raise Exception(f"Odd number of symbols ({len(pbstring)})")
msg = f"Odd number of symbols ({len(pbstring)})"
raise Exception(msg)
elif pbstring == "":
return {}

Expand All @@ -142,9 +142,11 @@ def _plugboard(pbstring: str) -> dict[str, str]:
tmppbl = set()
for i in pbstring:
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:
raise Exception(f"Duplicate symbol ({i})")
msg = f"Duplicate symbol ({i})"
raise Exception(msg)
else:
tmppbl.add(i)
del tmppbl
Expand Down
7 changes: 4 additions & 3 deletions ciphers/hill_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,11 @@ def check_determinant(self) -> None:

req_l = len(self.key_string)
if greatest_common_divisor(det, len(self.key_string)) != 1:
raise ValueError(
f"determinant modular {req_l} of encryption key({det}) is not co prime "
f"w.r.t {req_l}.\nTry another key."
msg = (
f"determinant modular {req_l} of encryption key({det}) "
f"is not co prime w.r.t {req_l}.\nTry another key."
)
raise ValueError(msg)

def process_text(self, text: str) -> str:
"""
Expand Down
6 changes: 4 additions & 2 deletions conversions/astronomical_length_scale_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

if from_sanitized not in METRIC_CONVERSION:
raise ValueError(
msg = (
f"Invalid 'from_type' value: {from_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
if to_sanitized not in METRIC_CONVERSION:
raise ValueError(
msg = (
f"Invalid 'to_type' value: {to_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
from_exponent = METRIC_CONVERSION[from_sanitized]
to_exponent = METRIC_CONVERSION[to_sanitized]
exponent = 1
Expand Down
6 changes: 4 additions & 2 deletions conversions/length_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = TYPE_CONVERSION.get(new_to, new_to)
if new_from not in METRIC_CONVERSION:
raise ValueError(
msg = (
f"Invalid 'from_type' value: {from_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
if new_to not in METRIC_CONVERSION:
raise ValueError(
msg = (
f"Invalid 'to_type' value: {to_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to


Expand Down
3 changes: 2 additions & 1 deletion conversions/speed_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,11 @@ def convert_speed(speed: float, unit_from: str, unit_to: str) -> float:
115.078
"""
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"Valid values are: {', '.join(speed_chart_inverse)}"
)
raise ValueError(msg)
return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3)


Expand Down
3 changes: 2 additions & 1 deletion conversions/weight_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,11 @@ def weight_conversion(from_type: str, to_type: str, value: float) -> float:
1.999999998903455
"""
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"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}"
)
raise ValueError(msg)
return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type]


Expand Down
6 changes: 4 additions & 2 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
elif label > node.label:
node.right = self._put(node.right, label, node)
else:
raise Exception(f"Node with label {label} already exists")
msg = f"Node with label {label} already exists"
raise Exception(msg)

return node

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

def _search(self, node: Node | None, label: int) -> Node:
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:
if label < node.label:
node = self._search(node.left, label)
Expand Down
3 changes: 2 additions & 1 deletion data_structures/binary_tree/binary_tree_mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict:
if not binary_tree:
raise ValueError("binary tree cannot be empty")
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_dict(binary_tree_mirror_dictionary, root)
return binary_tree_mirror_dictionary
Expand Down
3 changes: 2 additions & 1 deletion data_structures/disjoint_set/disjoint_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ def find_python_set(node: Node) -> set:
for s in sets:
if node.data in 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:
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/circular_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,25 +94,25 @@ def test_circular_linked_list() -> None:

try:
circular_linked_list.delete_front()
raise AssertionError() # This should not happen
raise AssertionError # This should not happen
except IndexError:
assert True # This should happen

try:
circular_linked_list.delete_tail()
raise AssertionError() # This should not happen
raise AssertionError # This should not happen
except IndexError:
assert True # This should happen

try:
circular_linked_list.delete_nth(-1)
raise AssertionError()
raise AssertionError
except IndexError:
assert True

try:
circular_linked_list.delete_nth(0)
raise AssertionError()
raise AssertionError
except IndexError:
assert True

Expand Down
Loading