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

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes:

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
Expand Down
2 changes: 1 addition & 1 deletion ciphers/caesar_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -225,7 +225,7 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str

if __name__ == "__main__":
while True:
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

# get user input
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/flip_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ def main() -> None:
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Success {index+1}/{len(new_images)} with {file_name}")
print(f"Success {index + 1}/{len(new_images)} with {file_name}")
annos_list = []
for anno in new_annos[index]:
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,7 +41,7 @@ def main() -> None:
file_name = path.split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}")
print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}")
annos_list = []
for anno in new_annos:
width = anno[3] - anno[1]
Expand Down
6 changes: 3 additions & 3 deletions data_structures/hashing/number_theory/prime_numbers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

if 1 < number < 4:
# 2 and 3 are primes
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/min_heap.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,9 +124,9 @@ def is_empty(self):
return len(self.heap) == 0

def decrease_key(self, node, new_value):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
assert self.heap[self.idx_of_element[node]].val > new_value, (
"newValue must be less that current value"
)
node.val = new_value
self.heap_dict[node.name] = new_value
self.sift_up(self.idx_of_element[node])
Expand Down
12 changes: 6 additions & 6 deletions data_structures/kd_tree/tests/test_kdtree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res
assert kdtree is not None, "Expected a KDNode, got None"

# Check if root has correct dimensions
assert (
len(kdtree.point) == num_dimensions
), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
assert len(kdtree.point) == num_dimensions, (
f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
)

# Check that the tree is balanced to some extent (simplistic check)
assert isinstance(
kdtree, KDNode
), f"Expected KDNode instance, got {type(kdtree)}"
assert isinstance(kdtree, KDNode), (
f"Expected KDNode instance, got {type(kdtree)}"
)


def test_nearest_neighbour_search():
Expand Down
24 changes: 12 additions & 12 deletions data_structures/suffix_tree/tests/test_suffix_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,37 +22,37 @@ def test_search_existing_patterns(self) -> None:
patterns = ["ana", "ban", "na"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should be found."
assert self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should be found."
)

def test_search_non_existing_patterns(self) -> None:
"""Test searching for patterns that do not exist in the suffix tree."""
patterns = ["xyz", "apple", "cat"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert not self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should not be found."
assert not self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should not be found."
)

def test_search_empty_pattern(self) -> None:
"""Test searching for an empty pattern."""
assert self.suffix_tree.search(""), "An empty pattern should be found."

def test_search_full_text(self) -> None:
"""Test searching for the full text."""
assert self.suffix_tree.search(
self.text
), "The full text should be found in the suffix tree."
assert self.suffix_tree.search(self.text), (
"The full text should be found in the suffix tree."
)

def test_search_substrings(self) -> None:
"""Test searching for substrings of the full text."""
substrings = ["ban", "ana", "a", "na"]
for substring in substrings:
with self.subTest(substring=substring):
assert self.suffix_tree.search(
substring
), f"Substring '{substring}' should be found."
assert self.suffix_tree.search(substring), (
f"Substring '{substring}' should be found."
)


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/climbing_stairs.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int:
...
AssertionError: number_of_steps needs to be positive integer, your input -7
"""
assert (
isinstance(number_of_steps, int) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
assert isinstance(number_of_steps, int) and number_of_steps > 0, (
f"number_of_steps needs to be positive integer, your input {number_of_steps}"
)
if number_of_steps == 1:
return 1
previous, current = 1, 1
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/iterating_through_submasks.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:

"""

assert (
isinstance(mask, int) and mask > 0
), f"mask needs to be positive integer, your input {mask}"
assert isinstance(mask, int) and mask > 0, (
f"mask needs to be positive integer, your input {mask}"
)

"""
first submask iterated will be mask itself then operation will be performed
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,7 +134,7 @@ def elapsed_time(msg: str) -> Iterator:

start = perf_counter_ns()
yield
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.")
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_discriminant_analysis.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -322,7 +322,7 @@ def main():
user_count = valid_input(
input_type=int,
condition=lambda x: x > 0,
input_msg=(f"Enter The number of instances for class_{i+1}: "),
input_msg=(f"Enter The number of instances for class_{i + 1}: "),
err_msg="Number of instances should be positive!",
)
counts.append(user_count)
Expand All@@ -333,7 +333,7 @@ def main():
for a in range(n_classes):
user_mean = valid_input(
input_type=float,
input_msg=(f"Enter the value of mean for class_{a+1}: "),
input_msg=(f"Enter the value of mean for class_{a + 1}: "),
err_msg="This is an invalid value.",
)
user_means.append(user_mean)
Expand Down
6 changes: 2 additions & 4 deletions maths/dual_number_automatic_differentiation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,8 @@ def __init__(self, real, rank):
self.duals = rank

def __repr__(self):
return (
f"{self.real}+"
f"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}"
)
s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1))
return f"{self.real}+{s}"

def reduce(self):
cur = self.duals.copy()
Expand Down
4 changes: 3 additions & 1 deletion maths/max_sum_sliding_window.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,4 +43,6 @@ def max_sum_in_array(array: list[int], k: int) -> int:
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
12 changes: 6 additions & 6 deletions maths/numerical_analysis/integration_by_simpson_approx.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo
AssertionError: precision should be positive integer your input : -1

"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert callable(function), (
f"the function(object) passed should be callable your input : {function}"
)
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
assert isinstance(precision, int) and precision > 0, (
f"precision should be positive integer your input : {precision}"
)

# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
Expand Down
12 changes: 6 additions & 6 deletions maths/prime_check.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,12 +73,12 @@ def test_primes(self):
def test_not_primes(self):
with pytest.raises(ValueError):
is_prime(-19)
assert not is_prime(
0
), "Zero doesn't have any positive factors, primes must have exactly two."
assert not is_prime(
1
), "One only has 1 positive factor, primes must have exactly two."
assert not is_prime(0), (
"Zero doesn't have any positive factors, primes must have exactly two."
)
assert not is_prime(1), (
"One only has 1 positive factor, primes must have exactly two."
)
assert not is_prime(2 * 2)
assert not is_prime(2 * 3)
assert not is_prime(3 * 3)
Expand Down
42 changes: 21 additions & 21 deletions maths/primelib.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -66,9 +66,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

status = True

Expand DownExpand Up@@ -254,9 +254,9 @@ def greatest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -296,9 +296,9 @@ def smallest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -399,9 +399,9 @@ def goldbach(number):
"""

# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)

ans = [] # this list will returned

Expand DownExpand Up@@ -525,9 +525,9 @@ def kg_v(number1, number2):
done.append(n)

# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)

return ans

Expand DownExpand Up@@ -574,9 +574,9 @@ def get_prime(n):
ans += 1

# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)

return ans

Expand DownExpand Up@@ -705,9 +705,9 @@ def is_perfect_number(number):
"""

# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)

divisors = get_divisors(number)

Expand Down
2 changes: 1 addition & 1 deletion matrix/matrix_based_game.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -273,7 +273,7 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) ->
size = int(input("Enter the size of the matrix: "))
validate_matrix_size(size)
print(f"Enter the {size} rows of the matrix:")
matrix = [input(f"Row {i+1}: ") for i in range(size)]
matrix = [input(f"Row {i + 1}: ") for i in range(size)]
validate_matrix_content(matrix, size)
moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ")
moves = parse_moves(moves_input)
Expand Down
6 changes: 3 additions & 3 deletions neural_network/input_data.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,9 +160,9 @@ def __init__(
self._num_examples = 10000
self.one_hot = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), f"images.shape: {images.shape} labels.shape: {labels.shape}"
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]

# Convert shape from [num examples, rows, columns, depth]
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_solutions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -94,6 +94,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None:
solution_module = convert_path_to_module(solution_path)
answer = str(solution_module.solution())
answer = hashlib.sha256(answer.encode()).hexdigest()
assert (
answer == expected
), f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
assert answer == expected, (
f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
[pre-commit.ci] pre-commit autoupdate -- ruff 2025 stable format by pre-commit-ci[bot] · Pull Request #12521 · TheAlgorithms/Python · GitHub
Skip to content
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes:

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
Expand Down
2 changes: 1 addition & 1 deletion ciphers/caesar_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -225,7 +225,7 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str

if __name__ == "__main__":
while True:
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

# get user input
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/flip_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ def main() -> None:
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Success {index+1}/{len(new_images)} with {file_name}")
print(f"Success {index + 1}/{len(new_images)} with {file_name}")
annos_list = []
for anno in new_annos[index]:
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,7 +41,7 @@ def main() -> None:
file_name = path.split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}")
print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}")
annos_list = []
for anno in new_annos:
width = anno[3] - anno[1]
Expand Down
6 changes: 3 additions & 3 deletions data_structures/hashing/number_theory/prime_numbers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

if 1 < number < 4:
# 2 and 3 are primes
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/min_heap.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,9 +124,9 @@ def is_empty(self):
return len(self.heap) == 0

def decrease_key(self, node, new_value):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
assert self.heap[self.idx_of_element[node]].val > new_value, (
"newValue must be less that current value"
)
node.val = new_value
self.heap_dict[node.name] = new_value
self.sift_up(self.idx_of_element[node])
Expand Down
12 changes: 6 additions & 6 deletions data_structures/kd_tree/tests/test_kdtree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res
assert kdtree is not None, "Expected a KDNode, got None"

# Check if root has correct dimensions
assert (
len(kdtree.point) == num_dimensions
), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
assert len(kdtree.point) == num_dimensions, (
f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
)

# Check that the tree is balanced to some extent (simplistic check)
assert isinstance(
kdtree, KDNode
), f"Expected KDNode instance, got {type(kdtree)}"
assert isinstance(kdtree, KDNode), (
f"Expected KDNode instance, got {type(kdtree)}"
)


def test_nearest_neighbour_search():
Expand Down
24 changes: 12 additions & 12 deletions data_structures/suffix_tree/tests/test_suffix_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,37 +22,37 @@ def test_search_existing_patterns(self) -> None:
patterns = ["ana", "ban", "na"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should be found."
assert self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should be found."
)

def test_search_non_existing_patterns(self) -> None:
"""Test searching for patterns that do not exist in the suffix tree."""
patterns = ["xyz", "apple", "cat"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert not self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should not be found."
assert not self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should not be found."
)

def test_search_empty_pattern(self) -> None:
"""Test searching for an empty pattern."""
assert self.suffix_tree.search(""), "An empty pattern should be found."

def test_search_full_text(self) -> None:
"""Test searching for the full text."""
assert self.suffix_tree.search(
self.text
), "The full text should be found in the suffix tree."
assert self.suffix_tree.search(self.text), (
"The full text should be found in the suffix tree."
)

def test_search_substrings(self) -> None:
"""Test searching for substrings of the full text."""
substrings = ["ban", "ana", "a", "na"]
for substring in substrings:
with self.subTest(substring=substring):
assert self.suffix_tree.search(
substring
), f"Substring '{substring}' should be found."
assert self.suffix_tree.search(substring), (
f"Substring '{substring}' should be found."
)


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/climbing_stairs.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int:
...
AssertionError: number_of_steps needs to be positive integer, your input -7
"""
assert (
isinstance(number_of_steps, int) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
assert isinstance(number_of_steps, int) and number_of_steps > 0, (
f"number_of_steps needs to be positive integer, your input {number_of_steps}"
)
if number_of_steps == 1:
return 1
previous, current = 1, 1
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/iterating_through_submasks.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:

"""

assert (
isinstance(mask, int) and mask > 0
), f"mask needs to be positive integer, your input {mask}"
assert isinstance(mask, int) and mask > 0, (
f"mask needs to be positive integer, your input {mask}"
)

"""
first submask iterated will be mask itself then operation will be performed
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,7 +134,7 @@ def elapsed_time(msg: str) -> Iterator:

start = perf_counter_ns()
yield
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.")
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_discriminant_analysis.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -322,7 +322,7 @@ def main():
user_count = valid_input(
input_type=int,
condition=lambda x: x > 0,
input_msg=(f"Enter The number of instances for class_{i+1}: "),
input_msg=(f"Enter The number of instances for class_{i + 1}: "),
err_msg="Number of instances should be positive!",
)
counts.append(user_count)
Expand All@@ -333,7 +333,7 @@ def main():
for a in range(n_classes):
user_mean = valid_input(
input_type=float,
input_msg=(f"Enter the value of mean for class_{a+1}: "),
input_msg=(f"Enter the value of mean for class_{a + 1}: "),
err_msg="This is an invalid value.",
)
user_means.append(user_mean)
Expand Down
6 changes: 2 additions & 4 deletions maths/dual_number_automatic_differentiation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,8 @@ def __init__(self, real, rank):
self.duals = rank

def __repr__(self):
return (
f"{self.real}+"
f"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}"
)
s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1))
return f"{self.real}+{s}"

def reduce(self):
cur = self.duals.copy()
Expand Down
4 changes: 3 additions & 1 deletion maths/max_sum_sliding_window.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,4 +43,6 @@ def max_sum_in_array(array: list[int], k: int) -> int:
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
12 changes: 6 additions & 6 deletions maths/numerical_analysis/integration_by_simpson_approx.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo
AssertionError: precision should be positive integer your input : -1

"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert callable(function), (
f"the function(object) passed should be callable your input : {function}"
)
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
assert isinstance(precision, int) and precision > 0, (
f"precision should be positive integer your input : {precision}"
)

# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
Expand Down
12 changes: 6 additions & 6 deletions maths/prime_check.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,12 +73,12 @@ def test_primes(self):
def test_not_primes(self):
with pytest.raises(ValueError):
is_prime(-19)
assert not is_prime(
0
), "Zero doesn't have any positive factors, primes must have exactly two."
assert not is_prime(
1
), "One only has 1 positive factor, primes must have exactly two."
assert not is_prime(0), (
"Zero doesn't have any positive factors, primes must have exactly two."
)
assert not is_prime(1), (
"One only has 1 positive factor, primes must have exactly two."
)
assert not is_prime(2 * 2)
assert not is_prime(2 * 3)
assert not is_prime(3 * 3)
Expand Down
42 changes: 21 additions & 21 deletions maths/primelib.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -66,9 +66,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

status = True

Expand DownExpand Up@@ -254,9 +254,9 @@ def greatest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -296,9 +296,9 @@ def smallest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -399,9 +399,9 @@ def goldbach(number):
"""

# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)

ans = [] # this list will returned

Expand DownExpand Up@@ -525,9 +525,9 @@ def kg_v(number1, number2):
done.append(n)

# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)

return ans

Expand DownExpand Up@@ -574,9 +574,9 @@ def get_prime(n):
ans += 1

# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)

return ans

Expand DownExpand Up@@ -705,9 +705,9 @@ def is_perfect_number(number):
"""

# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)

divisors = get_divisors(number)

Expand Down
2 changes: 1 addition & 1 deletion matrix/matrix_based_game.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -273,7 +273,7 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) ->
size = int(input("Enter the size of the matrix: "))
validate_matrix_size(size)
print(f"Enter the {size} rows of the matrix:")
matrix = [input(f"Row {i+1}: ") for i in range(size)]
matrix = [input(f"Row {i + 1}: ") for i in range(size)]
validate_matrix_content(matrix, size)
moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ")
moves = parse_moves(moves_input)
Expand Down
6 changes: 3 additions & 3 deletions neural_network/input_data.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,9 +160,9 @@ def __init__(
self._num_examples = 10000
self.one_hot = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), f"images.shape: {images.shape} labels.shape: {labels.shape}"
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]

# Convert shape from [num examples, rows, columns, depth]
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_solutions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -94,6 +94,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None:
solution_module = convert_path_to_module(solution_path)
answer = str(solution_module.solution())
answer = hashlib.sha256(answer.encode()).hexdigest()
assert (
answer == expected
), f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
assert answer == expected, (
f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [pre-commit.ci] pre-commit autoupdate -- ruff 2025 stable format by pre-commit-ci[bot] · Pull Request #12521 · TheAlgorithms/Python · GitHub
Skip to content
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes:

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
Expand Down
2 changes: 1 addition & 1 deletion ciphers/caesar_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -225,7 +225,7 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str

if __name__ == "__main__":
while True:
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

# get user input
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/flip_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ def main() -> None:
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Success {index+1}/{len(new_images)} with {file_name}")
print(f"Success {index + 1}/{len(new_images)} with {file_name}")
annos_list = []
for anno in new_annos[index]:
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,7 +41,7 @@ def main() -> None:
file_name = path.split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}")
print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}")
annos_list = []
for anno in new_annos:
width = anno[3] - anno[1]
Expand Down
6 changes: 3 additions & 3 deletions data_structures/hashing/number_theory/prime_numbers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

if 1 < number < 4:
# 2 and 3 are primes
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/min_heap.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,9 +124,9 @@ def is_empty(self):
return len(self.heap) == 0

def decrease_key(self, node, new_value):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
assert self.heap[self.idx_of_element[node]].val > new_value, (
"newValue must be less that current value"
)
node.val = new_value
self.heap_dict[node.name] = new_value
self.sift_up(self.idx_of_element[node])
Expand Down
12 changes: 6 additions & 6 deletions data_structures/kd_tree/tests/test_kdtree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res
assert kdtree is not None, "Expected a KDNode, got None"

# Check if root has correct dimensions
assert (
len(kdtree.point) == num_dimensions
), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
assert len(kdtree.point) == num_dimensions, (
f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
)

# Check that the tree is balanced to some extent (simplistic check)
assert isinstance(
kdtree, KDNode
), f"Expected KDNode instance, got {type(kdtree)}"
assert isinstance(kdtree, KDNode), (
f"Expected KDNode instance, got {type(kdtree)}"
)


def test_nearest_neighbour_search():
Expand Down
24 changes: 12 additions & 12 deletions data_structures/suffix_tree/tests/test_suffix_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,37 +22,37 @@ def test_search_existing_patterns(self) -> None:
patterns = ["ana", "ban", "na"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should be found."
assert self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should be found."
)

def test_search_non_existing_patterns(self) -> None:
"""Test searching for patterns that do not exist in the suffix tree."""
patterns = ["xyz", "apple", "cat"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert not self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should not be found."
assert not self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should not be found."
)

def test_search_empty_pattern(self) -> None:
"""Test searching for an empty pattern."""
assert self.suffix_tree.search(""), "An empty pattern should be found."

def test_search_full_text(self) -> None:
"""Test searching for the full text."""
assert self.suffix_tree.search(
self.text
), "The full text should be found in the suffix tree."
assert self.suffix_tree.search(self.text), (
"The full text should be found in the suffix tree."
)

def test_search_substrings(self) -> None:
"""Test searching for substrings of the full text."""
substrings = ["ban", "ana", "a", "na"]
for substring in substrings:
with self.subTest(substring=substring):
assert self.suffix_tree.search(
substring
), f"Substring '{substring}' should be found."
assert self.suffix_tree.search(substring), (
f"Substring '{substring}' should be found."
)


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/climbing_stairs.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int:
...
AssertionError: number_of_steps needs to be positive integer, your input -7
"""
assert (
isinstance(number_of_steps, int) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
assert isinstance(number_of_steps, int) and number_of_steps > 0, (
f"number_of_steps needs to be positive integer, your input {number_of_steps}"
)
if number_of_steps == 1:
return 1
previous, current = 1, 1
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/iterating_through_submasks.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:

"""

assert (
isinstance(mask, int) and mask > 0
), f"mask needs to be positive integer, your input {mask}"
assert isinstance(mask, int) and mask > 0, (
f"mask needs to be positive integer, your input {mask}"
)

"""
first submask iterated will be mask itself then operation will be performed
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,7 +134,7 @@ def elapsed_time(msg: str) -> Iterator:

start = perf_counter_ns()
yield
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.")
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_discriminant_analysis.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -322,7 +322,7 @@ def main():
user_count = valid_input(
input_type=int,
condition=lambda x: x > 0,
input_msg=(f"Enter The number of instances for class_{i+1}: "),
input_msg=(f"Enter The number of instances for class_{i + 1}: "),
err_msg="Number of instances should be positive!",
)
counts.append(user_count)
Expand All@@ -333,7 +333,7 @@ def main():
for a in range(n_classes):
user_mean = valid_input(
input_type=float,
input_msg=(f"Enter the value of mean for class_{a+1}: "),
input_msg=(f"Enter the value of mean for class_{a + 1}: "),
err_msg="This is an invalid value.",
)
user_means.append(user_mean)
Expand Down
6 changes: 2 additions & 4 deletions maths/dual_number_automatic_differentiation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,8 @@ def __init__(self, real, rank):
self.duals = rank

def __repr__(self):
return (
f"{self.real}+"
f"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}"
)
s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1))
return f"{self.real}+{s}"

def reduce(self):
cur = self.duals.copy()
Expand Down
4 changes: 3 additions & 1 deletion maths/max_sum_sliding_window.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,4 +43,6 @@ def max_sum_in_array(array: list[int], k: int) -> int:
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
12 changes: 6 additions & 6 deletions maths/numerical_analysis/integration_by_simpson_approx.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo
AssertionError: precision should be positive integer your input : -1

"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert callable(function), (
f"the function(object) passed should be callable your input : {function}"
)
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
assert isinstance(precision, int) and precision > 0, (
f"precision should be positive integer your input : {precision}"
)

# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
Expand Down
12 changes: 6 additions & 6 deletions maths/prime_check.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,12 +73,12 @@ def test_primes(self):
def test_not_primes(self):
with pytest.raises(ValueError):
is_prime(-19)
assert not is_prime(
0
), "Zero doesn't have any positive factors, primes must have exactly two."
assert not is_prime(
1
), "One only has 1 positive factor, primes must have exactly two."
assert not is_prime(0), (
"Zero doesn't have any positive factors, primes must have exactly two."
)
assert not is_prime(1), (
"One only has 1 positive factor, primes must have exactly two."
)
assert not is_prime(2 * 2)
assert not is_prime(2 * 3)
assert not is_prime(3 * 3)
Expand Down
42 changes: 21 additions & 21 deletions maths/primelib.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -66,9 +66,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

status = True

Expand DownExpand Up@@ -254,9 +254,9 @@ def greatest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -296,9 +296,9 @@ def smallest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -399,9 +399,9 @@ def goldbach(number):
"""

# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)

ans = [] # this list will returned

Expand DownExpand Up@@ -525,9 +525,9 @@ def kg_v(number1, number2):
done.append(n)

# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)

return ans

Expand DownExpand Up@@ -574,9 +574,9 @@ def get_prime(n):
ans += 1

# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)

return ans

Expand DownExpand Up@@ -705,9 +705,9 @@ def is_perfect_number(number):
"""

# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)

divisors = get_divisors(number)

Expand Down
2 changes: 1 addition & 1 deletion matrix/matrix_based_game.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -273,7 +273,7 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) ->
size = int(input("Enter the size of the matrix: "))
validate_matrix_size(size)
print(f"Enter the {size} rows of the matrix:")
matrix = [input(f"Row {i+1}: ") for i in range(size)]
matrix = [input(f"Row {i + 1}: ") for i in range(size)]
validate_matrix_content(matrix, size)
moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ")
moves = parse_moves(moves_input)
Expand Down
6 changes: 3 additions & 3 deletions neural_network/input_data.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,9 +160,9 @@ def __init__(
self._num_examples = 10000
self.one_hot = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), f"images.shape: {images.shape} labels.shape: {labels.shape}"
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]

# Convert shape from [num examples, rows, columns, depth]
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_solutions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -94,6 +94,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None:
solution_module = convert_path_to_module(solution_path)
answer = str(solution_module.solution())
answer = hashlib.sha256(answer.encode()).hexdigest()
assert (
answer == expected
), f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
assert answer == expected, (
f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [pre-commit.ci] pre-commit autoupdate -- ruff 2025 stable format by pre-commit-ci[bot] · Pull Request #12521 · TheAlgorithms/Python · GitHub
Skip to content
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes:

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
Expand Down
2 changes: 1 addition & 1 deletion ciphers/caesar_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -225,7 +225,7 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str

if __name__ == "__main__":
while True:
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

# get user input
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/flip_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ def main() -> None:
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Success {index+1}/{len(new_images)} with {file_name}")
print(f"Success {index + 1}/{len(new_images)} with {file_name}")
annos_list = []
for anno in new_annos[index]:
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,7 +41,7 @@ def main() -> None:
file_name = path.split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}")
print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}")
annos_list = []
for anno in new_annos:
width = anno[3] - anno[1]
Expand Down
6 changes: 3 additions & 3 deletions data_structures/hashing/number_theory/prime_numbers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

if 1 < number < 4:
# 2 and 3 are primes
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/min_heap.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,9 +124,9 @@ def is_empty(self):
return len(self.heap) == 0

def decrease_key(self, node, new_value):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
assert self.heap[self.idx_of_element[node]].val > new_value, (
"newValue must be less that current value"
)
node.val = new_value
self.heap_dict[node.name] = new_value
self.sift_up(self.idx_of_element[node])
Expand Down
12 changes: 6 additions & 6 deletions data_structures/kd_tree/tests/test_kdtree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res
assert kdtree is not None, "Expected a KDNode, got None"

# Check if root has correct dimensions
assert (
len(kdtree.point) == num_dimensions
), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
assert len(kdtree.point) == num_dimensions, (
f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
)

# Check that the tree is balanced to some extent (simplistic check)
assert isinstance(
kdtree, KDNode
), f"Expected KDNode instance, got {type(kdtree)}"
assert isinstance(kdtree, KDNode), (
f"Expected KDNode instance, got {type(kdtree)}"
)


def test_nearest_neighbour_search():
Expand Down
24 changes: 12 additions & 12 deletions data_structures/suffix_tree/tests/test_suffix_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,37 +22,37 @@ def test_search_existing_patterns(self) -> None:
patterns = ["ana", "ban", "na"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should be found."
assert self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should be found."
)

def test_search_non_existing_patterns(self) -> None:
"""Test searching for patterns that do not exist in the suffix tree."""
patterns = ["xyz", "apple", "cat"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert not self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should not be found."
assert not self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should not be found."
)

def test_search_empty_pattern(self) -> None:
"""Test searching for an empty pattern."""
assert self.suffix_tree.search(""), "An empty pattern should be found."

def test_search_full_text(self) -> None:
"""Test searching for the full text."""
assert self.suffix_tree.search(
self.text
), "The full text should be found in the suffix tree."
assert self.suffix_tree.search(self.text), (
"The full text should be found in the suffix tree."
)

def test_search_substrings(self) -> None:
"""Test searching for substrings of the full text."""
substrings = ["ban", "ana", "a", "na"]
for substring in substrings:
with self.subTest(substring=substring):
assert self.suffix_tree.search(
substring
), f"Substring '{substring}' should be found."
assert self.suffix_tree.search(substring), (
f"Substring '{substring}' should be found."
)


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/climbing_stairs.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int:
...
AssertionError: number_of_steps needs to be positive integer, your input -7
"""
assert (
isinstance(number_of_steps, int) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
assert isinstance(number_of_steps, int) and number_of_steps > 0, (
f"number_of_steps needs to be positive integer, your input {number_of_steps}"
)
if number_of_steps == 1:
return 1
previous, current = 1, 1
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/iterating_through_submasks.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:

"""

assert (
isinstance(mask, int) and mask > 0
), f"mask needs to be positive integer, your input {mask}"
assert isinstance(mask, int) and mask > 0, (
f"mask needs to be positive integer, your input {mask}"
)

"""
first submask iterated will be mask itself then operation will be performed
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,7 +134,7 @@ def elapsed_time(msg: str) -> Iterator:

start = perf_counter_ns()
yield
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.")
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_discriminant_analysis.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -322,7 +322,7 @@ def main():
user_count = valid_input(
input_type=int,
condition=lambda x: x > 0,
input_msg=(f"Enter The number of instances for class_{i+1}: "),
input_msg=(f"Enter The number of instances for class_{i + 1}: "),
err_msg="Number of instances should be positive!",
)
counts.append(user_count)
Expand All@@ -333,7 +333,7 @@ def main():
for a in range(n_classes):
user_mean = valid_input(
input_type=float,
input_msg=(f"Enter the value of mean for class_{a+1}: "),
input_msg=(f"Enter the value of mean for class_{a + 1}: "),
err_msg="This is an invalid value.",
)
user_means.append(user_mean)
Expand Down
6 changes: 2 additions & 4 deletions maths/dual_number_automatic_differentiation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,8 @@ def __init__(self, real, rank):
self.duals = rank

def __repr__(self):
return (
f"{self.real}+"
f"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}"
)
s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1))
return f"{self.real}+{s}"

def reduce(self):
cur = self.duals.copy()
Expand Down
4 changes: 3 additions & 1 deletion maths/max_sum_sliding_window.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,4 +43,6 @@ def max_sum_in_array(array: list[int], k: int) -> int:
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
12 changes: 6 additions & 6 deletions maths/numerical_analysis/integration_by_simpson_approx.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo
AssertionError: precision should be positive integer your input : -1

"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert callable(function), (
f"the function(object) passed should be callable your input : {function}"
)
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
assert isinstance(precision, int) and precision > 0, (
f"precision should be positive integer your input : {precision}"
)

# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
Expand Down
12 changes: 6 additions & 6 deletions maths/prime_check.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,12 +73,12 @@ def test_primes(self):
def test_not_primes(self):
with pytest.raises(ValueError):
is_prime(-19)
assert not is_prime(
0
), "Zero doesn't have any positive factors, primes must have exactly two."
assert not is_prime(
1
), "One only has 1 positive factor, primes must have exactly two."
assert not is_prime(0), (
"Zero doesn't have any positive factors, primes must have exactly two."
)
assert not is_prime(1), (
"One only has 1 positive factor, primes must have exactly two."
)
assert not is_prime(2 * 2)
assert not is_prime(2 * 3)
assert not is_prime(3 * 3)
Expand Down
42 changes: 21 additions & 21 deletions maths/primelib.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -66,9 +66,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

status = True

Expand DownExpand Up@@ -254,9 +254,9 @@ def greatest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -296,9 +296,9 @@ def smallest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -399,9 +399,9 @@ def goldbach(number):
"""

# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)

ans = [] # this list will returned

Expand DownExpand Up@@ -525,9 +525,9 @@ def kg_v(number1, number2):
done.append(n)

# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)

return ans

Expand DownExpand Up@@ -574,9 +574,9 @@ def get_prime(n):
ans += 1

# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)

return ans

Expand DownExpand Up@@ -705,9 +705,9 @@ def is_perfect_number(number):
"""

# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)

divisors = get_divisors(number)

Expand Down
2 changes: 1 addition & 1 deletion matrix/matrix_based_game.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -273,7 +273,7 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) ->
size = int(input("Enter the size of the matrix: "))
validate_matrix_size(size)
print(f"Enter the {size} rows of the matrix:")
matrix = [input(f"Row {i+1}: ") for i in range(size)]
matrix = [input(f"Row {i + 1}: ") for i in range(size)]
validate_matrix_content(matrix, size)
moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ")
moves = parse_moves(moves_input)
Expand Down
6 changes: 3 additions & 3 deletions neural_network/input_data.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,9 +160,9 @@ def __init__(
self._num_examples = 10000
self.one_hot = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), f"images.shape: {images.shape} labels.shape: {labels.shape}"
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]

# Convert shape from [num examples, rows, columns, depth]
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_solutions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -94,6 +94,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None:
solution_module = convert_path_to_module(solution_path)
answer = str(solution_module.solution())
answer = hashlib.sha256(answer.encode()).hexdigest()
assert (
answer == expected
), f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
assert answer == expected, (
f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' [pre-commit.ci] pre-commit autoupdate -- ruff 2025 stable format by pre-commit-ci[bot] · Pull Request #12521 · TheAlgorithms/Python · GitHub
Skip to content
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes:

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
Expand Down
2 changes: 1 addition & 1 deletion ciphers/caesar_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -225,7 +225,7 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str

if __name__ == "__main__":
while True:
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

# get user input
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/flip_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ def main() -> None:
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Success {index+1}/{len(new_images)} with {file_name}")
print(f"Success {index + 1}/{len(new_images)} with {file_name}")
annos_list = []
for anno in new_annos[index]:
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,7 +41,7 @@ def main() -> None:
file_name = path.split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}")
print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}")
annos_list = []
for anno in new_annos:
width = anno[3] - anno[1]
Expand Down
6 changes: 3 additions & 3 deletions data_structures/hashing/number_theory/prime_numbers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

if 1 < number < 4:
# 2 and 3 are primes
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/min_heap.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,9 +124,9 @@ def is_empty(self):
return len(self.heap) == 0

def decrease_key(self, node, new_value):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
assert self.heap[self.idx_of_element[node]].val > new_value, (
"newValue must be less that current value"
)
node.val = new_value
self.heap_dict[node.name] = new_value
self.sift_up(self.idx_of_element[node])
Expand Down
12 changes: 6 additions & 6 deletions data_structures/kd_tree/tests/test_kdtree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res
assert kdtree is not None, "Expected a KDNode, got None"

# Check if root has correct dimensions
assert (
len(kdtree.point) == num_dimensions
), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
assert len(kdtree.point) == num_dimensions, (
f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
)

# Check that the tree is balanced to some extent (simplistic check)
assert isinstance(
kdtree, KDNode
), f"Expected KDNode instance, got {type(kdtree)}"
assert isinstance(kdtree, KDNode), (
f"Expected KDNode instance, got {type(kdtree)}"
)


def test_nearest_neighbour_search():
Expand Down
24 changes: 12 additions & 12 deletions data_structures/suffix_tree/tests/test_suffix_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,37 +22,37 @@ def test_search_existing_patterns(self) -> None:
patterns = ["ana", "ban", "na"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should be found."
assert self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should be found."
)

def test_search_non_existing_patterns(self) -> None:
"""Test searching for patterns that do not exist in the suffix tree."""
patterns = ["xyz", "apple", "cat"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert not self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should not be found."
assert not self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should not be found."
)

def test_search_empty_pattern(self) -> None:
"""Test searching for an empty pattern."""
assert self.suffix_tree.search(""), "An empty pattern should be found."

def test_search_full_text(self) -> None:
"""Test searching for the full text."""
assert self.suffix_tree.search(
self.text
), "The full text should be found in the suffix tree."
assert self.suffix_tree.search(self.text), (
"The full text should be found in the suffix tree."
)

def test_search_substrings(self) -> None:
"""Test searching for substrings of the full text."""
substrings = ["ban", "ana", "a", "na"]
for substring in substrings:
with self.subTest(substring=substring):
assert self.suffix_tree.search(
substring
), f"Substring '{substring}' should be found."
assert self.suffix_tree.search(substring), (
f"Substring '{substring}' should be found."
)


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/climbing_stairs.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int:
...
AssertionError: number_of_steps needs to be positive integer, your input -7
"""
assert (
isinstance(number_of_steps, int) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
assert isinstance(number_of_steps, int) and number_of_steps > 0, (
f"number_of_steps needs to be positive integer, your input {number_of_steps}"
)
if number_of_steps == 1:
return 1
previous, current = 1, 1
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/iterating_through_submasks.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:

"""

assert (
isinstance(mask, int) and mask > 0
), f"mask needs to be positive integer, your input {mask}"
assert isinstance(mask, int) and mask > 0, (
f"mask needs to be positive integer, your input {mask}"
)

"""
first submask iterated will be mask itself then operation will be performed
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,7 +134,7 @@ def elapsed_time(msg: str) -> Iterator:

start = perf_counter_ns()
yield
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.")
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_discriminant_analysis.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -322,7 +322,7 @@ def main():
user_count = valid_input(
input_type=int,
condition=lambda x: x > 0,
input_msg=(f"Enter The number of instances for class_{i+1}: "),
input_msg=(f"Enter The number of instances for class_{i + 1}: "),
err_msg="Number of instances should be positive!",
)
counts.append(user_count)
Expand All@@ -333,7 +333,7 @@ def main():
for a in range(n_classes):
user_mean = valid_input(
input_type=float,
input_msg=(f"Enter the value of mean for class_{a+1}: "),
input_msg=(f"Enter the value of mean for class_{a + 1}: "),
err_msg="This is an invalid value.",
)
user_means.append(user_mean)
Expand Down
6 changes: 2 additions & 4 deletions maths/dual_number_automatic_differentiation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,8 @@ def __init__(self, real, rank):
self.duals = rank

def __repr__(self):
return (
f"{self.real}+"
f"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}"
)
s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1))
return f"{self.real}+{s}"

def reduce(self):
cur = self.duals.copy()
Expand Down
4 changes: 3 additions & 1 deletion maths/max_sum_sliding_window.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,4 +43,6 @@ def max_sum_in_array(array: list[int], k: int) -> int:
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
12 changes: 6 additions & 6 deletions maths/numerical_analysis/integration_by_simpson_approx.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo
AssertionError: precision should be positive integer your input : -1

"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert callable(function), (
f"the function(object) passed should be callable your input : {function}"
)
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
assert isinstance(precision, int) and precision > 0, (
f"precision should be positive integer your input : {precision}"
)

# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
Expand Down
12 changes: 6 additions & 6 deletions maths/prime_check.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,12 +73,12 @@ def test_primes(self):
def test_not_primes(self):
with pytest.raises(ValueError):
is_prime(-19)
assert not is_prime(
0
), "Zero doesn't have any positive factors, primes must have exactly two."
assert not is_prime(
1
), "One only has 1 positive factor, primes must have exactly two."
assert not is_prime(0), (
"Zero doesn't have any positive factors, primes must have exactly two."
)
assert not is_prime(1), (
"One only has 1 positive factor, primes must have exactly two."
)
assert not is_prime(2 * 2)
assert not is_prime(2 * 3)
assert not is_prime(3 * 3)
Expand Down
42 changes: 21 additions & 21 deletions maths/primelib.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -66,9 +66,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

status = True

Expand DownExpand Up@@ -254,9 +254,9 @@ def greatest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -296,9 +296,9 @@ def smallest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -399,9 +399,9 @@ def goldbach(number):
"""

# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)

ans = [] # this list will returned

Expand DownExpand Up@@ -525,9 +525,9 @@ def kg_v(number1, number2):
done.append(n)

# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)

return ans

Expand DownExpand Up@@ -574,9 +574,9 @@ def get_prime(n):
ans += 1

# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)

return ans

Expand DownExpand Up@@ -705,9 +705,9 @@ def is_perfect_number(number):
"""

# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)

divisors = get_divisors(number)

Expand Down
2 changes: 1 addition & 1 deletion matrix/matrix_based_game.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -273,7 +273,7 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) ->
size = int(input("Enter the size of the matrix: "))
validate_matrix_size(size)
print(f"Enter the {size} rows of the matrix:")
matrix = [input(f"Row {i+1}: ") for i in range(size)]
matrix = [input(f"Row {i + 1}: ") for i in range(size)]
validate_matrix_content(matrix, size)
moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ")
moves = parse_moves(moves_input)
Expand Down
6 changes: 3 additions & 3 deletions neural_network/input_data.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,9 +160,9 @@ def __init__(
self._num_examples = 10000
self.one_hot = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), f"images.shape: {images.shape} labels.shape: {labels.shape}"
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]

# Convert shape from [num examples, rows, columns, depth]
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_solutions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -94,6 +94,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None:
solution_module = convert_path_to_module(solution_path)
answer = str(solution_module.solution())
answer = hashlib.sha256(answer.encode()).hexdigest()
assert (
answer == expected
), f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
assert answer == expected, (
f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [pre-commit.ci] pre-commit autoupdate -- ruff 2025 stable format by pre-commit-ci[bot] · Pull Request #12521 · TheAlgorithms/Python · GitHub
Skip to content
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes:

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
Expand Down
2 changes: 1 addition & 1 deletion ciphers/caesar_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -225,7 +225,7 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str

if __name__ == "__main__":
while True:
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

# get user input
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/flip_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ def main() -> None:
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Success {index+1}/{len(new_images)} with {file_name}")
print(f"Success {index + 1}/{len(new_images)} with {file_name}")
annos_list = []
for anno in new_annos[index]:
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,7 +41,7 @@ def main() -> None:
file_name = path.split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}")
print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}")
annos_list = []
for anno in new_annos:
width = anno[3] - anno[1]
Expand Down
6 changes: 3 additions & 3 deletions data_structures/hashing/number_theory/prime_numbers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

if 1 < number < 4:
# 2 and 3 are primes
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/min_heap.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,9 +124,9 @@ def is_empty(self):
return len(self.heap) == 0

def decrease_key(self, node, new_value):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
assert self.heap[self.idx_of_element[node]].val > new_value, (
"newValue must be less that current value"
)
node.val = new_value
self.heap_dict[node.name] = new_value
self.sift_up(self.idx_of_element[node])
Expand Down
12 changes: 6 additions & 6 deletions data_structures/kd_tree/tests/test_kdtree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res
assert kdtree is not None, "Expected a KDNode, got None"

# Check if root has correct dimensions
assert (
len(kdtree.point) == num_dimensions
), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
assert len(kdtree.point) == num_dimensions, (
f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
)

# Check that the tree is balanced to some extent (simplistic check)
assert isinstance(
kdtree, KDNode
), f"Expected KDNode instance, got {type(kdtree)}"
assert isinstance(kdtree, KDNode), (
f"Expected KDNode instance, got {type(kdtree)}"
)


def test_nearest_neighbour_search():
Expand Down
24 changes: 12 additions & 12 deletions data_structures/suffix_tree/tests/test_suffix_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,37 +22,37 @@ def test_search_existing_patterns(self) -> None:
patterns = ["ana", "ban", "na"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should be found."
assert self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should be found."
)

def test_search_non_existing_patterns(self) -> None:
"""Test searching for patterns that do not exist in the suffix tree."""
patterns = ["xyz", "apple", "cat"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert not self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should not be found."
assert not self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should not be found."
)

def test_search_empty_pattern(self) -> None:
"""Test searching for an empty pattern."""
assert self.suffix_tree.search(""), "An empty pattern should be found."

def test_search_full_text(self) -> None:
"""Test searching for the full text."""
assert self.suffix_tree.search(
self.text
), "The full text should be found in the suffix tree."
assert self.suffix_tree.search(self.text), (
"The full text should be found in the suffix tree."
)

def test_search_substrings(self) -> None:
"""Test searching for substrings of the full text."""
substrings = ["ban", "ana", "a", "na"]
for substring in substrings:
with self.subTest(substring=substring):
assert self.suffix_tree.search(
substring
), f"Substring '{substring}' should be found."
assert self.suffix_tree.search(substring), (
f"Substring '{substring}' should be found."
)


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/climbing_stairs.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int:
...
AssertionError: number_of_steps needs to be positive integer, your input -7
"""
assert (
isinstance(number_of_steps, int) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
assert isinstance(number_of_steps, int) and number_of_steps > 0, (
f"number_of_steps needs to be positive integer, your input {number_of_steps}"
)
if number_of_steps == 1:
return 1
previous, current = 1, 1
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/iterating_through_submasks.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:

"""

assert (
isinstance(mask, int) and mask > 0
), f"mask needs to be positive integer, your input {mask}"
assert isinstance(mask, int) and mask > 0, (
f"mask needs to be positive integer, your input {mask}"
)

"""
first submask iterated will be mask itself then operation will be performed
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,7 +134,7 @@ def elapsed_time(msg: str) -> Iterator:

start = perf_counter_ns()
yield
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.")
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_discriminant_analysis.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -322,7 +322,7 @@ def main():
user_count = valid_input(
input_type=int,
condition=lambda x: x > 0,
input_msg=(f"Enter The number of instances for class_{i+1}: "),
input_msg=(f"Enter The number of instances for class_{i + 1}: "),
err_msg="Number of instances should be positive!",
)
counts.append(user_count)
Expand All@@ -333,7 +333,7 @@ def main():
for a in range(n_classes):
user_mean = valid_input(
input_type=float,
input_msg=(f"Enter the value of mean for class_{a+1}: "),
input_msg=(f"Enter the value of mean for class_{a + 1}: "),
err_msg="This is an invalid value.",
)
user_means.append(user_mean)
Expand Down
6 changes: 2 additions & 4 deletions maths/dual_number_automatic_differentiation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,8 @@ def __init__(self, real, rank):
self.duals = rank

def __repr__(self):
return (
f"{self.real}+"
f"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}"
)
s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1))
return f"{self.real}+{s}"

def reduce(self):
cur = self.duals.copy()
Expand Down
4 changes: 3 additions & 1 deletion maths/max_sum_sliding_window.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,4 +43,6 @@ def max_sum_in_array(array: list[int], k: int) -> int:
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
12 changes: 6 additions & 6 deletions maths/numerical_analysis/integration_by_simpson_approx.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo
AssertionError: precision should be positive integer your input : -1

"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert callable(function), (
f"the function(object) passed should be callable your input : {function}"
)
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
assert isinstance(precision, int) and precision > 0, (
f"precision should be positive integer your input : {precision}"
)

# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
Expand Down
12 changes: 6 additions & 6 deletions maths/prime_check.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,12 +73,12 @@ def test_primes(self):
def test_not_primes(self):
with pytest.raises(ValueError):
is_prime(-19)
assert not is_prime(
0
), "Zero doesn't have any positive factors, primes must have exactly two."
assert not is_prime(
1
), "One only has 1 positive factor, primes must have exactly two."
assert not is_prime(0), (
"Zero doesn't have any positive factors, primes must have exactly two."
)
assert not is_prime(1), (
"One only has 1 positive factor, primes must have exactly two."
)
assert not is_prime(2 * 2)
assert not is_prime(2 * 3)
assert not is_prime(3 * 3)
Expand Down
42 changes: 21 additions & 21 deletions maths/primelib.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -66,9 +66,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

status = True

Expand DownExpand Up@@ -254,9 +254,9 @@ def greatest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -296,9 +296,9 @@ def smallest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -399,9 +399,9 @@ def goldbach(number):
"""

# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)

ans = [] # this list will returned

Expand DownExpand Up@@ -525,9 +525,9 @@ def kg_v(number1, number2):
done.append(n)

# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)

return ans

Expand DownExpand Up@@ -574,9 +574,9 @@ def get_prime(n):
ans += 1

# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)

return ans

Expand DownExpand Up@@ -705,9 +705,9 @@ def is_perfect_number(number):
"""

# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)

divisors = get_divisors(number)

Expand Down
2 changes: 1 addition & 1 deletion matrix/matrix_based_game.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -273,7 +273,7 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) ->
size = int(input("Enter the size of the matrix: "))
validate_matrix_size(size)
print(f"Enter the {size} rows of the matrix:")
matrix = [input(f"Row {i+1}: ") for i in range(size)]
matrix = [input(f"Row {i + 1}: ") for i in range(size)]
validate_matrix_content(matrix, size)
moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ")
moves = parse_moves(moves_input)
Expand Down
6 changes: 3 additions & 3 deletions neural_network/input_data.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,9 +160,9 @@ def __init__(
self._num_examples = 10000
self.one_hot = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), f"images.shape: {images.shape} labels.shape: {labels.shape}"
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]

# Convert shape from [num examples, rows, columns, depth]
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_solutions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -94,6 +94,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None:
solution_module = convert_path_to_module(solution_path)
answer = str(solution_module.solution())
answer = hashlib.sha256(answer.encode()).hexdigest()
assert (
answer == expected
), f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
assert answer == expected, (
f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [pre-commit.ci] pre-commit autoupdate -- ruff 2025 stable format by pre-commit-ci[bot] · Pull Request #12521 · TheAlgorithms/Python · GitHub
Skip to content
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes:

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
Expand Down
2 changes: 1 addition & 1 deletion ciphers/caesar_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -225,7 +225,7 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str

if __name__ == "__main__":
while True:
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

# get user input
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/flip_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ def main() -> None:
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Success {index+1}/{len(new_images)} with {file_name}")
print(f"Success {index + 1}/{len(new_images)} with {file_name}")
annos_list = []
for anno in new_annos[index]:
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,7 +41,7 @@ def main() -> None:
file_name = path.split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}")
print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}")
annos_list = []
for anno in new_annos:
width = anno[3] - anno[1]
Expand Down
6 changes: 3 additions & 3 deletions data_structures/hashing/number_theory/prime_numbers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

if 1 < number < 4:
# 2 and 3 are primes
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/min_heap.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,9 +124,9 @@ def is_empty(self):
return len(self.heap) == 0

def decrease_key(self, node, new_value):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
assert self.heap[self.idx_of_element[node]].val > new_value, (
"newValue must be less that current value"
)
node.val = new_value
self.heap_dict[node.name] = new_value
self.sift_up(self.idx_of_element[node])
Expand Down
12 changes: 6 additions & 6 deletions data_structures/kd_tree/tests/test_kdtree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res
assert kdtree is not None, "Expected a KDNode, got None"

# Check if root has correct dimensions
assert (
len(kdtree.point) == num_dimensions
), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
assert len(kdtree.point) == num_dimensions, (
f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
)

# Check that the tree is balanced to some extent (simplistic check)
assert isinstance(
kdtree, KDNode
), f"Expected KDNode instance, got {type(kdtree)}"
assert isinstance(kdtree, KDNode), (
f"Expected KDNode instance, got {type(kdtree)}"
)


def test_nearest_neighbour_search():
Expand Down
24 changes: 12 additions & 12 deletions data_structures/suffix_tree/tests/test_suffix_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,37 +22,37 @@ def test_search_existing_patterns(self) -> None:
patterns = ["ana", "ban", "na"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should be found."
assert self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should be found."
)

def test_search_non_existing_patterns(self) -> None:
"""Test searching for patterns that do not exist in the suffix tree."""
patterns = ["xyz", "apple", "cat"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert not self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should not be found."
assert not self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should not be found."
)

def test_search_empty_pattern(self) -> None:
"""Test searching for an empty pattern."""
assert self.suffix_tree.search(""), "An empty pattern should be found."

def test_search_full_text(self) -> None:
"""Test searching for the full text."""
assert self.suffix_tree.search(
self.text
), "The full text should be found in the suffix tree."
assert self.suffix_tree.search(self.text), (
"The full text should be found in the suffix tree."
)

def test_search_substrings(self) -> None:
"""Test searching for substrings of the full text."""
substrings = ["ban", "ana", "a", "na"]
for substring in substrings:
with self.subTest(substring=substring):
assert self.suffix_tree.search(
substring
), f"Substring '{substring}' should be found."
assert self.suffix_tree.search(substring), (
f"Substring '{substring}' should be found."
)


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/climbing_stairs.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int:
...
AssertionError: number_of_steps needs to be positive integer, your input -7
"""
assert (
isinstance(number_of_steps, int) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
assert isinstance(number_of_steps, int) and number_of_steps > 0, (
f"number_of_steps needs to be positive integer, your input {number_of_steps}"
)
if number_of_steps == 1:
return 1
previous, current = 1, 1
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/iterating_through_submasks.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:

"""

assert (
isinstance(mask, int) and mask > 0
), f"mask needs to be positive integer, your input {mask}"
assert isinstance(mask, int) and mask > 0, (
f"mask needs to be positive integer, your input {mask}"
)

"""
first submask iterated will be mask itself then operation will be performed
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,7 +134,7 @@ def elapsed_time(msg: str) -> Iterator:

start = perf_counter_ns()
yield
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.")
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_discriminant_analysis.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -322,7 +322,7 @@ def main():
user_count = valid_input(
input_type=int,
condition=lambda x: x > 0,
input_msg=(f"Enter The number of instances for class_{i+1}: "),
input_msg=(f"Enter The number of instances for class_{i + 1}: "),
err_msg="Number of instances should be positive!",
)
counts.append(user_count)
Expand All@@ -333,7 +333,7 @@ def main():
for a in range(n_classes):
user_mean = valid_input(
input_type=float,
input_msg=(f"Enter the value of mean for class_{a+1}: "),
input_msg=(f"Enter the value of mean for class_{a + 1}: "),
err_msg="This is an invalid value.",
)
user_means.append(user_mean)
Expand Down
6 changes: 2 additions & 4 deletions maths/dual_number_automatic_differentiation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,8 @@ def __init__(self, real, rank):
self.duals = rank

def __repr__(self):
return (
f"{self.real}+"
f"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}"
)
s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1))
return f"{self.real}+{s}"

def reduce(self):
cur = self.duals.copy()
Expand Down
4 changes: 3 additions & 1 deletion maths/max_sum_sliding_window.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,4 +43,6 @@ def max_sum_in_array(array: list[int], k: int) -> int:
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
12 changes: 6 additions & 6 deletions maths/numerical_analysis/integration_by_simpson_approx.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo
AssertionError: precision should be positive integer your input : -1

"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert callable(function), (
f"the function(object) passed should be callable your input : {function}"
)
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
assert isinstance(precision, int) and precision > 0, (
f"precision should be positive integer your input : {precision}"
)

# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
Expand Down
12 changes: 6 additions & 6 deletions maths/prime_check.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,12 +73,12 @@ def test_primes(self):
def test_not_primes(self):
with pytest.raises(ValueError):
is_prime(-19)
assert not is_prime(
0
), "Zero doesn't have any positive factors, primes must have exactly two."
assert not is_prime(
1
), "One only has 1 positive factor, primes must have exactly two."
assert not is_prime(0), (
"Zero doesn't have any positive factors, primes must have exactly two."
)
assert not is_prime(1), (
"One only has 1 positive factor, primes must have exactly two."
)
assert not is_prime(2 * 2)
assert not is_prime(2 * 3)
assert not is_prime(3 * 3)
Expand Down
42 changes: 21 additions & 21 deletions maths/primelib.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -66,9 +66,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

status = True

Expand DownExpand Up@@ -254,9 +254,9 @@ def greatest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -296,9 +296,9 @@ def smallest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -399,9 +399,9 @@ def goldbach(number):
"""

# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)

ans = [] # this list will returned

Expand DownExpand Up@@ -525,9 +525,9 @@ def kg_v(number1, number2):
done.append(n)

# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)

return ans

Expand DownExpand Up@@ -574,9 +574,9 @@ def get_prime(n):
ans += 1

# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)

return ans

Expand DownExpand Up@@ -705,9 +705,9 @@ def is_perfect_number(number):
"""

# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)

divisors = get_divisors(number)

Expand Down
2 changes: 1 addition & 1 deletion matrix/matrix_based_game.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -273,7 +273,7 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) ->
size = int(input("Enter the size of the matrix: "))
validate_matrix_size(size)
print(f"Enter the {size} rows of the matrix:")
matrix = [input(f"Row {i+1}: ") for i in range(size)]
matrix = [input(f"Row {i + 1}: ") for i in range(size)]
validate_matrix_content(matrix, size)
moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ")
moves = parse_moves(moves_input)
Expand Down
6 changes: 3 additions & 3 deletions neural_network/input_data.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,9 +160,9 @@ def __init__(
self._num_examples = 10000
self.one_hot = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), f"images.shape: {images.shape} labels.shape: {labels.shape}"
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]

# Convert shape from [num examples, rows, columns, depth]
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_solutions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -94,6 +94,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None:
solution_module = convert_path_to_module(solution_path)
answer = str(solution_module.solution())
answer = hashlib.sha256(answer.encode()).hexdigest()
assert (
answer == expected
), f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
assert answer == expected, (
f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); [pre-commit.ci] pre-commit autoupdate -- ruff 2025 stable format by pre-commit-ci[bot] · Pull Request #12521 · TheAlgorithms/Python · GitHub
Skip to content
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
12 changes: 6 additions & 6 deletions ciphers/base64_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes:

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
Expand Down
2 changes: 1 addition & 1 deletion ciphers/caesar_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -225,7 +225,7 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str

if __name__ == "__main__":
while True:
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

# get user input
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/flip_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ def main() -> None:
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Success {index+1}/{len(new_images)} with {file_name}")
print(f"Success {index + 1}/{len(new_images)} with {file_name}")
annos_list = []
for anno in new_annos[index]:
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,7 +41,7 @@ def main() -> None:
file_name = path.split(os.sep)[-1].rsplit(".", 1)[0]
file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}")
print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}")
annos_list = []
for anno in new_annos:
width = anno[3] - anno[1]
Expand Down
6 changes: 3 additions & 3 deletions data_structures/hashing/number_theory/prime_numbers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

if 1 < number < 4:
# 2 and 3 are primes
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/min_heap.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,9 +124,9 @@ def is_empty(self):
return len(self.heap) == 0

def decrease_key(self, node, new_value):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
assert self.heap[self.idx_of_element[node]].val > new_value, (
"newValue must be less that current value"
)
node.val = new_value
self.heap_dict[node.name] = new_value
self.sift_up(self.idx_of_element[node])
Expand Down
12 changes: 6 additions & 6 deletions data_structures/kd_tree/tests/test_kdtree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res
assert kdtree is not None, "Expected a KDNode, got None"

# Check if root has correct dimensions
assert (
len(kdtree.point) == num_dimensions
), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
assert len(kdtree.point) == num_dimensions, (
f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}"
)

# Check that the tree is balanced to some extent (simplistic check)
assert isinstance(
kdtree, KDNode
), f"Expected KDNode instance, got {type(kdtree)}"
assert isinstance(kdtree, KDNode), (
f"Expected KDNode instance, got {type(kdtree)}"
)


def test_nearest_neighbour_search():
Expand Down
24 changes: 12 additions & 12 deletions data_structures/suffix_tree/tests/test_suffix_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,37 +22,37 @@ def test_search_existing_patterns(self) -> None:
patterns = ["ana", "ban", "na"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should be found."
assert self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should be found."
)

def test_search_non_existing_patterns(self) -> None:
"""Test searching for patterns that do not exist in the suffix tree."""
patterns = ["xyz", "apple", "cat"]
for pattern in patterns:
with self.subTest(pattern=pattern):
assert not self.suffix_tree.search(
pattern
), f"Pattern '{pattern}' should not be found."
assert not self.suffix_tree.search(pattern), (
f"Pattern '{pattern}' should not be found."
)

def test_search_empty_pattern(self) -> None:
"""Test searching for an empty pattern."""
assert self.suffix_tree.search(""), "An empty pattern should be found."

def test_search_full_text(self) -> None:
"""Test searching for the full text."""
assert self.suffix_tree.search(
self.text
), "The full text should be found in the suffix tree."
assert self.suffix_tree.search(self.text), (
"The full text should be found in the suffix tree."
)

def test_search_substrings(self) -> None:
"""Test searching for substrings of the full text."""
substrings = ["ban", "ana", "a", "na"]
for substring in substrings:
with self.subTest(substring=substring):
assert self.suffix_tree.search(
substring
), f"Substring '{substring}' should be found."
assert self.suffix_tree.search(substring), (
f"Substring '{substring}' should be found."
)


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/climbing_stairs.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int:
...
AssertionError: number_of_steps needs to be positive integer, your input -7
"""
assert (
isinstance(number_of_steps, int) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
assert isinstance(number_of_steps, int) and number_of_steps > 0, (
f"number_of_steps needs to be positive integer, your input {number_of_steps}"
)
if number_of_steps == 1:
return 1
previous, current = 1, 1
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/iterating_through_submasks.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:

"""

assert (
isinstance(mask, int) and mask > 0
), f"mask needs to be positive integer, your input {mask}"
assert isinstance(mask, int) and mask > 0, (
f"mask needs to be positive integer, your input {mask}"
)

"""
first submask iterated will be mask itself then operation will be performed
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,7 +134,7 @@ def elapsed_time(msg: str) -> Iterator:

start = perf_counter_ns()
yield
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.")
print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_discriminant_analysis.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -322,7 +322,7 @@ def main():
user_count = valid_input(
input_type=int,
condition=lambda x: x > 0,
input_msg=(f"Enter The number of instances for class_{i+1}: "),
input_msg=(f"Enter The number of instances for class_{i + 1}: "),
err_msg="Number of instances should be positive!",
)
counts.append(user_count)
Expand All@@ -333,7 +333,7 @@ def main():
for a in range(n_classes):
user_mean = valid_input(
input_type=float,
input_msg=(f"Enter the value of mean for class_{a+1}: "),
input_msg=(f"Enter the value of mean for class_{a + 1}: "),
err_msg="This is an invalid value.",
)
user_means.append(user_mean)
Expand Down
6 changes: 2 additions & 4 deletions maths/dual_number_automatic_differentiation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,8 @@ def __init__(self, real, rank):
self.duals = rank

def __repr__(self):
return (
f"{self.real}+"
f"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}"
)
s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1))
return f"{self.real}+{s}"

def reduce(self):
cur = self.duals.copy()
Expand Down
4 changes: 3 additions & 1 deletion maths/max_sum_sliding_window.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,4 +43,6 @@ def max_sum_in_array(array: list[int], k: int) -> int:
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
12 changes: 6 additions & 6 deletions maths/numerical_analysis/integration_by_simpson_approx.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo
AssertionError: precision should be positive integer your input : -1

"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert callable(function), (
f"the function(object) passed should be callable your input : {function}"
)
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
assert isinstance(precision, int) and precision > 0, (
f"precision should be positive integer your input : {precision}"
)

# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
Expand Down
12 changes: 6 additions & 6 deletions maths/prime_check.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,12 +73,12 @@ def test_primes(self):
def test_not_primes(self):
with pytest.raises(ValueError):
is_prime(-19)
assert not is_prime(
0
), "Zero doesn't have any positive factors, primes must have exactly two."
assert not is_prime(
1
), "One only has 1 positive factor, primes must have exactly two."
assert not is_prime(0), (
"Zero doesn't have any positive factors, primes must have exactly two."
)
assert not is_prime(1), (
"One only has 1 positive factor, primes must have exactly two."
)
assert not is_prime(2 * 2)
assert not is_prime(2 * 3)
assert not is_prime(3 * 3)
Expand Down
42 changes: 21 additions & 21 deletions maths/primelib.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -66,9 +66,9 @@ def is_prime(number: int) -> bool:
"""

# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)

status = True

Expand DownExpand Up@@ -254,9 +254,9 @@ def greatest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -296,9 +296,9 @@ def smallest_prime_factor(number):
"""

# precondition
assert isinstance(number, int) and (
number>= 0
), "'number' must been an int and >= 0"
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)

ans = 0

Expand DownExpand Up@@ -399,9 +399,9 @@ def goldbach(number):
"""

# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)

ans = [] # this list will returned

Expand DownExpand Up@@ -525,9 +525,9 @@ def kg_v(number1, number2):
done.append(n)

# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)

return ans

Expand DownExpand Up@@ -574,9 +574,9 @@ def get_prime(n):
ans += 1

# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)

return ans

Expand DownExpand Up@@ -705,9 +705,9 @@ def is_perfect_number(number):
"""

# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)

divisors = get_divisors(number)

Expand Down
2 changes: 1 addition & 1 deletion matrix/matrix_based_game.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -273,7 +273,7 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) ->
size = int(input("Enter the size of the matrix: "))
validate_matrix_size(size)
print(f"Enter the {size} rows of the matrix:")
matrix = [input(f"Row {i+1}: ") for i in range(size)]
matrix = [input(f"Row {i + 1}: ") for i in range(size)]
validate_matrix_content(matrix, size)
moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ")
moves = parse_moves(moves_input)
Expand Down
6 changes: 3 additions & 3 deletions neural_network/input_data.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,9 +160,9 @@ def __init__(
self._num_examples = 10000
self.one_hot = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), f"images.shape: {images.shape} labels.shape: {labels.shape}"
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]

# Convert shape from [num examples, rows, columns, depth]
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_solutions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -94,6 +94,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None:
solution_module = convert_path_to_module(solution_path)
answer = str(solution_module.solution())
answer = hashlib.sha256(answer.encode()).hexdigest()
assert (
answer == expected
), f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
assert answer == expected, (
f"Expected solution to {problem_number} to have hash {expected}, got {answer}"
)
Loading