Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.6.0
hooks:
- id: mypy
args:
Expand Down
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -532,6 +532,7 @@
* [Logistic Regression](machine_learning/logistic_regression.py)
* Loss Functions
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
* [Mfcc](machine_learning/mfcc.py)
Expand Down
6 changes: 4 additions & 2 deletions blockchain/diophantine_equation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
(1, -2, 3)

"""
assert a >= 0 and b >= 0
assert a >= 0
assert b >= 0

if b == 0:
d, x, y = a, 1, 0
Expand All@@ -92,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
x = q
y = p - q * (a // b)

assert a % d == 0 and b % d == 0
assert a % d == 0
assert b % d == 0
assert d == a * x + b * y

return (d, x, y)
Expand Down
18 changes: 12 additions & 6 deletions ciphers/xor_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,7 +38,8 @@ def encrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -56,7 +57,8 @@ def decrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
assert isinstance(key, int)
assert isinstance(content, list)

key = key or self.__key or 1

Expand All@@ -74,7 +76,8 @@ def encrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -99,7 +102,8 @@ def decrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -125,7 +129,8 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
Expand All@@ -148,7 +153,8 @@ def decrypt_file(self, file: str, key: int) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,8 @@ def decimal_to_hexadecimal(decimal: float) -> str:
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
assert isinstance(decimal, (int, float))
assert decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
Expand Down
28 changes: 15 additions & 13 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import unittest
from collections.abc import Iterator

import pytest


class Node:
def __init__(self, label: int, parent: Node | None) -> None:
Expand DownExpand Up@@ -78,7 +80,7 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
node.right = self._put(node.right, label, node)
else:
msg = f"Node with label {label} already exists"
raise Exception(msg)
raise ValueError(msg)

return node

Expand All@@ -95,14 +97,14 @@ def search(self, label: int) -> Node:
>>> node = t.search(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
return self._search(self.root, label)

def _search(self, node: Node | None, label: int) -> Node:
if node is None:
msg = f"Node with label {label} does not exist"
raise Exception(msg)
raise ValueError(msg)
else:
if label < node.label:
node = self._search(node.left, label)
Expand All@@ -124,7 +126,7 @@ def remove(self, label: int) -> None:
>>> t.remove(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
node = self.search(label)
if node.right and node.left:
Expand DownExpand Up@@ -179,7 +181,7 @@ def exists(self, label: int) -> bool:
try:
self.search(label)
return True
except Exception:
except ValueError:
return False

def get_max_label(self) -> int:
Expand All@@ -190,15 +192,15 @@ def get_max_label(self) -> int:
>>> t.get_max_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.right is not None:
Expand All@@ -214,15 +216,15 @@ def get_min_label(self) -> int:
>>> t.get_min_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.left is not None:
Expand DownExpand Up@@ -359,7 +361,7 @@ def test_put(self) -> None:
assert t.root.left.left.parent == t.root.left
assert t.root.left.left.label == 1

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.put(1)

def test_search(self) -> None:
Expand All@@ -371,7 +373,7 @@ def test_search(self) -> None:
node = t.search(13)
assert node.label == 13

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.search(2)

def test_remove(self) -> None:
Expand DownExpand Up@@ -517,7 +519,7 @@ def test_get_max_label(self) -> None:
assert t.get_max_label() == 14

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_max_label()

def test_get_min_label(self) -> None:
Expand All@@ -526,7 +528,7 @@ def test_get_min_label(self) -> None:
assert t.get_min_label() == 1

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_min_label()

def test_inorder_traversal(self) -> None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/hashing/tests/test_hash_map.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,14 +65,14 @@ def _run_operation(obj, fun, *args):

@pytest.mark.parametrize(
"operations",
(
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
Expand Down
6 changes: 4 additions & 2 deletions data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,7 +124,8 @@ def delete_nth(self, index: int = 0) -> Any:
if not 0 <= index < len(self):
raise IndexError("list index out of range.")

assert self.head is not None and self.tail is not None
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
Expand All@@ -137,7 +138,8 @@ def delete_nth(self, index: int = 0) -> Any:
for _ in range(index - 1):
assert temp is not None
temp = temp.next
assert temp is not None and temp.next is not None
assert temp is not None
assert temp.next is not None
delete_node = temp.next
temp.next = temp.next.next
if index == len(self) - 1: # Delete at tail
Expand Down
3 changes: 2 additions & 1 deletion digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,8 @@ def test_median_filter():

def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
assert grad.any()
assert theta.any()


def test_sepia():
Expand Down
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" + '
Add Ruff rules for pandas-vet and pytest-style by cclauss · Pull Request #10281 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.6.0
hooks:
- id: mypy
args:
Expand Down
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -532,6 +532,7 @@
* [Logistic Regression](machine_learning/logistic_regression.py)
* Loss Functions
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
* [Mfcc](machine_learning/mfcc.py)
Expand Down
6 changes: 4 additions & 2 deletions blockchain/diophantine_equation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
(1, -2, 3)

"""
assert a >= 0 and b >= 0
assert a >= 0
assert b >= 0

if b == 0:
d, x, y = a, 1, 0
Expand All@@ -92,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
x = q
y = p - q * (a // b)

assert a % d == 0 and b % d == 0
assert a % d == 0
assert b % d == 0
assert d == a * x + b * y

return (d, x, y)
Expand Down
18 changes: 12 additions & 6 deletions ciphers/xor_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,7 +38,8 @@ def encrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -56,7 +57,8 @@ def decrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
assert isinstance(key, int)
assert isinstance(content, list)

key = key or self.__key or 1

Expand All@@ -74,7 +76,8 @@ def encrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -99,7 +102,8 @@ def decrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -125,7 +129,8 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
Expand All@@ -148,7 +153,8 @@ def decrypt_file(self, file: str, key: int) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,8 @@ def decimal_to_hexadecimal(decimal: float) -> str:
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
assert isinstance(decimal, (int, float))
assert decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
Expand Down
28 changes: 15 additions & 13 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import unittest
from collections.abc import Iterator

import pytest


class Node:
def __init__(self, label: int, parent: Node | None) -> None:
Expand DownExpand Up@@ -78,7 +80,7 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
node.right = self._put(node.right, label, node)
else:
msg = f"Node with label {label} already exists"
raise Exception(msg)
raise ValueError(msg)

return node

Expand All@@ -95,14 +97,14 @@ def search(self, label: int) -> Node:
>>> node = t.search(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
return self._search(self.root, label)

def _search(self, node: Node | None, label: int) -> Node:
if node is None:
msg = f"Node with label {label} does not exist"
raise Exception(msg)
raise ValueError(msg)
else:
if label < node.label:
node = self._search(node.left, label)
Expand All@@ -124,7 +126,7 @@ def remove(self, label: int) -> None:
>>> t.remove(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
node = self.search(label)
if node.right and node.left:
Expand DownExpand Up@@ -179,7 +181,7 @@ def exists(self, label: int) -> bool:
try:
self.search(label)
return True
except Exception:
except ValueError:
return False

def get_max_label(self) -> int:
Expand All@@ -190,15 +192,15 @@ def get_max_label(self) -> int:
>>> t.get_max_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.right is not None:
Expand All@@ -214,15 +216,15 @@ def get_min_label(self) -> int:
>>> t.get_min_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.left is not None:
Expand DownExpand Up@@ -359,7 +361,7 @@ def test_put(self) -> None:
assert t.root.left.left.parent == t.root.left
assert t.root.left.left.label == 1

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.put(1)

def test_search(self) -> None:
Expand All@@ -371,7 +373,7 @@ def test_search(self) -> None:
node = t.search(13)
assert node.label == 13

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.search(2)

def test_remove(self) -> None:
Expand DownExpand Up@@ -517,7 +519,7 @@ def test_get_max_label(self) -> None:
assert t.get_max_label() == 14

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_max_label()

def test_get_min_label(self) -> None:
Expand All@@ -526,7 +528,7 @@ def test_get_min_label(self) -> None:
assert t.get_min_label() == 1

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_min_label()

def test_inorder_traversal(self) -> None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/hashing/tests/test_hash_map.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,14 +65,14 @@ def _run_operation(obj, fun, *args):

@pytest.mark.parametrize(
"operations",
(
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
Expand Down
6 changes: 4 additions & 2 deletions data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,7 +124,8 @@ def delete_nth(self, index: int = 0) -> Any:
if not 0 <= index < len(self):
raise IndexError("list index out of range.")

assert self.head is not None and self.tail is not None
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
Expand All@@ -137,7 +138,8 @@ def delete_nth(self, index: int = 0) -> Any:
for _ in range(index - 1):
assert temp is not None
temp = temp.next
assert temp is not None and temp.next is not None
assert temp is not None
assert temp.next is not None
delete_node = temp.next
temp.next = temp.next.next
if index == len(self) - 1: # Delete at tail
Expand Down
3 changes: 2 additions & 1 deletion digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,8 @@ def test_median_filter():

def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
assert grad.any()
assert theta.any()


def test_sepia():
Expand Down
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('^' + ".*" + ' Add Ruff rules for pandas-vet and pytest-style by cclauss · Pull Request #10281 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.6.0
hooks:
- id: mypy
args:
Expand Down
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -532,6 +532,7 @@
* [Logistic Regression](machine_learning/logistic_regression.py)
* Loss Functions
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
* [Mfcc](machine_learning/mfcc.py)
Expand Down
6 changes: 4 additions & 2 deletions blockchain/diophantine_equation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
(1, -2, 3)

"""
assert a >= 0 and b >= 0
assert a >= 0
assert b >= 0

if b == 0:
d, x, y = a, 1, 0
Expand All@@ -92,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
x = q
y = p - q * (a // b)

assert a % d == 0 and b % d == 0
assert a % d == 0
assert b % d == 0
assert d == a * x + b * y

return (d, x, y)
Expand Down
18 changes: 12 additions & 6 deletions ciphers/xor_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,7 +38,8 @@ def encrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -56,7 +57,8 @@ def decrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
assert isinstance(key, int)
assert isinstance(content, list)

key = key or self.__key or 1

Expand All@@ -74,7 +76,8 @@ def encrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -99,7 +102,8 @@ def decrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -125,7 +129,8 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
Expand All@@ -148,7 +153,8 @@ def decrypt_file(self, file: str, key: int) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,8 @@ def decimal_to_hexadecimal(decimal: float) -> str:
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
assert isinstance(decimal, (int, float))
assert decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
Expand Down
28 changes: 15 additions & 13 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import unittest
from collections.abc import Iterator

import pytest


class Node:
def __init__(self, label: int, parent: Node | None) -> None:
Expand DownExpand Up@@ -78,7 +80,7 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
node.right = self._put(node.right, label, node)
else:
msg = f"Node with label {label} already exists"
raise Exception(msg)
raise ValueError(msg)

return node

Expand All@@ -95,14 +97,14 @@ def search(self, label: int) -> Node:
>>> node = t.search(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
return self._search(self.root, label)

def _search(self, node: Node | None, label: int) -> Node:
if node is None:
msg = f"Node with label {label} does not exist"
raise Exception(msg)
raise ValueError(msg)
else:
if label < node.label:
node = self._search(node.left, label)
Expand All@@ -124,7 +126,7 @@ def remove(self, label: int) -> None:
>>> t.remove(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
node = self.search(label)
if node.right and node.left:
Expand DownExpand Up@@ -179,7 +181,7 @@ def exists(self, label: int) -> bool:
try:
self.search(label)
return True
except Exception:
except ValueError:
return False

def get_max_label(self) -> int:
Expand All@@ -190,15 +192,15 @@ def get_max_label(self) -> int:
>>> t.get_max_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.right is not None:
Expand All@@ -214,15 +216,15 @@ def get_min_label(self) -> int:
>>> t.get_min_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.left is not None:
Expand DownExpand Up@@ -359,7 +361,7 @@ def test_put(self) -> None:
assert t.root.left.left.parent == t.root.left
assert t.root.left.left.label == 1

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.put(1)

def test_search(self) -> None:
Expand All@@ -371,7 +373,7 @@ def test_search(self) -> None:
node = t.search(13)
assert node.label == 13

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.search(2)

def test_remove(self) -> None:
Expand DownExpand Up@@ -517,7 +519,7 @@ def test_get_max_label(self) -> None:
assert t.get_max_label() == 14

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_max_label()

def test_get_min_label(self) -> None:
Expand All@@ -526,7 +528,7 @@ def test_get_min_label(self) -> None:
assert t.get_min_label() == 1

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_min_label()

def test_inorder_traversal(self) -> None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/hashing/tests/test_hash_map.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,14 +65,14 @@ def _run_operation(obj, fun, *args):

@pytest.mark.parametrize(
"operations",
(
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
Expand Down
6 changes: 4 additions & 2 deletions data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,7 +124,8 @@ def delete_nth(self, index: int = 0) -> Any:
if not 0 <= index < len(self):
raise IndexError("list index out of range.")

assert self.head is not None and self.tail is not None
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
Expand All@@ -137,7 +138,8 @@ def delete_nth(self, index: int = 0) -> Any:
for _ in range(index - 1):
assert temp is not None
temp = temp.next
assert temp is not None and temp.next is not None
assert temp is not None
assert temp.next is not None
delete_node = temp.next
temp.next = temp.next.next
if index == len(self) - 1: # Delete at tail
Expand Down
3 changes: 2 additions & 1 deletion digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,8 @@ def test_median_filter():

def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
assert grad.any()
assert theta.any()


def test_sepia():
Expand Down
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('^' + ".*" + ' Add Ruff rules for pandas-vet and pytest-style by cclauss · Pull Request #10281 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.6.0
hooks:
- id: mypy
args:
Expand Down
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -532,6 +532,7 @@
* [Logistic Regression](machine_learning/logistic_regression.py)
* Loss Functions
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
* [Mfcc](machine_learning/mfcc.py)
Expand Down
6 changes: 4 additions & 2 deletions blockchain/diophantine_equation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
(1, -2, 3)

"""
assert a >= 0 and b >= 0
assert a >= 0
assert b >= 0

if b == 0:
d, x, y = a, 1, 0
Expand All@@ -92,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
x = q
y = p - q * (a // b)

assert a % d == 0 and b % d == 0
assert a % d == 0
assert b % d == 0
assert d == a * x + b * y

return (d, x, y)
Expand Down
18 changes: 12 additions & 6 deletions ciphers/xor_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,7 +38,8 @@ def encrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -56,7 +57,8 @@ def decrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
assert isinstance(key, int)
assert isinstance(content, list)

key = key or self.__key or 1

Expand All@@ -74,7 +76,8 @@ def encrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -99,7 +102,8 @@ def decrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -125,7 +129,8 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
Expand All@@ -148,7 +153,8 @@ def decrypt_file(self, file: str, key: int) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,8 @@ def decimal_to_hexadecimal(decimal: float) -> str:
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
assert isinstance(decimal, (int, float))
assert decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
Expand Down
28 changes: 15 additions & 13 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import unittest
from collections.abc import Iterator

import pytest


class Node:
def __init__(self, label: int, parent: Node | None) -> None:
Expand DownExpand Up@@ -78,7 +80,7 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
node.right = self._put(node.right, label, node)
else:
msg = f"Node with label {label} already exists"
raise Exception(msg)
raise ValueError(msg)

return node

Expand All@@ -95,14 +97,14 @@ def search(self, label: int) -> Node:
>>> node = t.search(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
return self._search(self.root, label)

def _search(self, node: Node | None, label: int) -> Node:
if node is None:
msg = f"Node with label {label} does not exist"
raise Exception(msg)
raise ValueError(msg)
else:
if label < node.label:
node = self._search(node.left, label)
Expand All@@ -124,7 +126,7 @@ def remove(self, label: int) -> None:
>>> t.remove(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
node = self.search(label)
if node.right and node.left:
Expand DownExpand Up@@ -179,7 +181,7 @@ def exists(self, label: int) -> bool:
try:
self.search(label)
return True
except Exception:
except ValueError:
return False

def get_max_label(self) -> int:
Expand All@@ -190,15 +192,15 @@ def get_max_label(self) -> int:
>>> t.get_max_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.right is not None:
Expand All@@ -214,15 +216,15 @@ def get_min_label(self) -> int:
>>> t.get_min_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.left is not None:
Expand DownExpand Up@@ -359,7 +361,7 @@ def test_put(self) -> None:
assert t.root.left.left.parent == t.root.left
assert t.root.left.left.label == 1

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.put(1)

def test_search(self) -> None:
Expand All@@ -371,7 +373,7 @@ def test_search(self) -> None:
node = t.search(13)
assert node.label == 13

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.search(2)

def test_remove(self) -> None:
Expand DownExpand Up@@ -517,7 +519,7 @@ def test_get_max_label(self) -> None:
assert t.get_max_label() == 14

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_max_label()

def test_get_min_label(self) -> None:
Expand All@@ -526,7 +528,7 @@ def test_get_min_label(self) -> None:
assert t.get_min_label() == 1

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_min_label()

def test_inorder_traversal(self) -> None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/hashing/tests/test_hash_map.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,14 +65,14 @@ def _run_operation(obj, fun, *args):

@pytest.mark.parametrize(
"operations",
(
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
Expand Down
6 changes: 4 additions & 2 deletions data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,7 +124,8 @@ def delete_nth(self, index: int = 0) -> Any:
if not 0 <= index < len(self):
raise IndexError("list index out of range.")

assert self.head is not None and self.tail is not None
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
Expand All@@ -137,7 +138,8 @@ def delete_nth(self, index: int = 0) -> Any:
for _ in range(index - 1):
assert temp is not None
temp = temp.next
assert temp is not None and temp.next is not None
assert temp is not None
assert temp.next is not None
delete_node = temp.next
temp.next = temp.next.next
if index == len(self) - 1: # Delete at tail
Expand Down
3 changes: 2 additions & 1 deletion digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,8 @@ def test_median_filter():

def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
assert grad.any()
assert theta.any()


def test_sepia():
Expand Down
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" + ' Add Ruff rules for pandas-vet and pytest-style by cclauss · Pull Request #10281 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.6.0
hooks:
- id: mypy
args:
Expand Down
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -532,6 +532,7 @@
* [Logistic Regression](machine_learning/logistic_regression.py)
* Loss Functions
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
* [Mfcc](machine_learning/mfcc.py)
Expand Down
6 changes: 4 additions & 2 deletions blockchain/diophantine_equation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
(1, -2, 3)

"""
assert a >= 0 and b >= 0
assert a >= 0
assert b >= 0

if b == 0:
d, x, y = a, 1, 0
Expand All@@ -92,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
x = q
y = p - q * (a // b)

assert a % d == 0 and b % d == 0
assert a % d == 0
assert b % d == 0
assert d == a * x + b * y

return (d, x, y)
Expand Down
18 changes: 12 additions & 6 deletions ciphers/xor_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,7 +38,8 @@ def encrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -56,7 +57,8 @@ def decrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
assert isinstance(key, int)
assert isinstance(content, list)

key = key or self.__key or 1

Expand All@@ -74,7 +76,8 @@ def encrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -99,7 +102,8 @@ def decrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -125,7 +129,8 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
Expand All@@ -148,7 +153,8 @@ def decrypt_file(self, file: str, key: int) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,8 @@ def decimal_to_hexadecimal(decimal: float) -> str:
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
assert isinstance(decimal, (int, float))
assert decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
Expand Down
28 changes: 15 additions & 13 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import unittest
from collections.abc import Iterator

import pytest


class Node:
def __init__(self, label: int, parent: Node | None) -> None:
Expand DownExpand Up@@ -78,7 +80,7 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
node.right = self._put(node.right, label, node)
else:
msg = f"Node with label {label} already exists"
raise Exception(msg)
raise ValueError(msg)

return node

Expand All@@ -95,14 +97,14 @@ def search(self, label: int) -> Node:
>>> node = t.search(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
return self._search(self.root, label)

def _search(self, node: Node | None, label: int) -> Node:
if node is None:
msg = f"Node with label {label} does not exist"
raise Exception(msg)
raise ValueError(msg)
else:
if label < node.label:
node = self._search(node.left, label)
Expand All@@ -124,7 +126,7 @@ def remove(self, label: int) -> None:
>>> t.remove(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
node = self.search(label)
if node.right and node.left:
Expand DownExpand Up@@ -179,7 +181,7 @@ def exists(self, label: int) -> bool:
try:
self.search(label)
return True
except Exception:
except ValueError:
return False

def get_max_label(self) -> int:
Expand All@@ -190,15 +192,15 @@ def get_max_label(self) -> int:
>>> t.get_max_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.right is not None:
Expand All@@ -214,15 +216,15 @@ def get_min_label(self) -> int:
>>> t.get_min_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.left is not None:
Expand DownExpand Up@@ -359,7 +361,7 @@ def test_put(self) -> None:
assert t.root.left.left.parent == t.root.left
assert t.root.left.left.label == 1

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.put(1)

def test_search(self) -> None:
Expand All@@ -371,7 +373,7 @@ def test_search(self) -> None:
node = t.search(13)
assert node.label == 13

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.search(2)

def test_remove(self) -> None:
Expand DownExpand Up@@ -517,7 +519,7 @@ def test_get_max_label(self) -> None:
assert t.get_max_label() == 14

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_max_label()

def test_get_min_label(self) -> None:
Expand All@@ -526,7 +528,7 @@ def test_get_min_label(self) -> None:
assert t.get_min_label() == 1

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_min_label()

def test_inorder_traversal(self) -> None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/hashing/tests/test_hash_map.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,14 +65,14 @@ def _run_operation(obj, fun, *args):

@pytest.mark.parametrize(
"operations",
(
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
Expand Down
6 changes: 4 additions & 2 deletions data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,7 +124,8 @@ def delete_nth(self, index: int = 0) -> Any:
if not 0 <= index < len(self):
raise IndexError("list index out of range.")

assert self.head is not None and self.tail is not None
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
Expand All@@ -137,7 +138,8 @@ def delete_nth(self, index: int = 0) -> Any:
for _ in range(index - 1):
assert temp is not None
temp = temp.next
assert temp is not None and temp.next is not None
assert temp is not None
assert temp.next is not None
delete_node = temp.next
temp.next = temp.next.next
if index == len(self) - 1: # Delete at tail
Expand Down
3 changes: 2 additions & 1 deletion digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,8 @@ def test_median_filter():

def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
assert grad.any()
assert theta.any()


def test_sepia():
Expand Down
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('^' + ".*" + ' Add Ruff rules for pandas-vet and pytest-style by cclauss · Pull Request #10281 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.6.0
hooks:
- id: mypy
args:
Expand Down
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -532,6 +532,7 @@
* [Logistic Regression](machine_learning/logistic_regression.py)
* Loss Functions
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
* [Mfcc](machine_learning/mfcc.py)
Expand Down
6 changes: 4 additions & 2 deletions blockchain/diophantine_equation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
(1, -2, 3)

"""
assert a >= 0 and b >= 0
assert a >= 0
assert b >= 0

if b == 0:
d, x, y = a, 1, 0
Expand All@@ -92,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
x = q
y = p - q * (a // b)

assert a % d == 0 and b % d == 0
assert a % d == 0
assert b % d == 0
assert d == a * x + b * y

return (d, x, y)
Expand Down
18 changes: 12 additions & 6 deletions ciphers/xor_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,7 +38,8 @@ def encrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -56,7 +57,8 @@ def decrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
assert isinstance(key, int)
assert isinstance(content, list)

key = key or self.__key or 1

Expand All@@ -74,7 +76,8 @@ def encrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -99,7 +102,8 @@ def decrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -125,7 +129,8 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
Expand All@@ -148,7 +153,8 @@ def decrypt_file(self, file: str, key: int) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,8 @@ def decimal_to_hexadecimal(decimal: float) -> str:
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
assert isinstance(decimal, (int, float))
assert decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
Expand Down
28 changes: 15 additions & 13 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import unittest
from collections.abc import Iterator

import pytest


class Node:
def __init__(self, label: int, parent: Node | None) -> None:
Expand DownExpand Up@@ -78,7 +80,7 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
node.right = self._put(node.right, label, node)
else:
msg = f"Node with label {label} already exists"
raise Exception(msg)
raise ValueError(msg)

return node

Expand All@@ -95,14 +97,14 @@ def search(self, label: int) -> Node:
>>> node = t.search(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
return self._search(self.root, label)

def _search(self, node: Node | None, label: int) -> Node:
if node is None:
msg = f"Node with label {label} does not exist"
raise Exception(msg)
raise ValueError(msg)
else:
if label < node.label:
node = self._search(node.left, label)
Expand All@@ -124,7 +126,7 @@ def remove(self, label: int) -> None:
>>> t.remove(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
node = self.search(label)
if node.right and node.left:
Expand DownExpand Up@@ -179,7 +181,7 @@ def exists(self, label: int) -> bool:
try:
self.search(label)
return True
except Exception:
except ValueError:
return False

def get_max_label(self) -> int:
Expand All@@ -190,15 +192,15 @@ def get_max_label(self) -> int:
>>> t.get_max_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.right is not None:
Expand All@@ -214,15 +216,15 @@ def get_min_label(self) -> int:
>>> t.get_min_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.left is not None:
Expand DownExpand Up@@ -359,7 +361,7 @@ def test_put(self) -> None:
assert t.root.left.left.parent == t.root.left
assert t.root.left.left.label == 1

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.put(1)

def test_search(self) -> None:
Expand All@@ -371,7 +373,7 @@ def test_search(self) -> None:
node = t.search(13)
assert node.label == 13

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.search(2)

def test_remove(self) -> None:
Expand DownExpand Up@@ -517,7 +519,7 @@ def test_get_max_label(self) -> None:
assert t.get_max_label() == 14

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_max_label()

def test_get_min_label(self) -> None:
Expand All@@ -526,7 +528,7 @@ def test_get_min_label(self) -> None:
assert t.get_min_label() == 1

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_min_label()

def test_inorder_traversal(self) -> None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/hashing/tests/test_hash_map.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,14 +65,14 @@ def _run_operation(obj, fun, *args):

@pytest.mark.parametrize(
"operations",
(
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
Expand Down
6 changes: 4 additions & 2 deletions data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,7 +124,8 @@ def delete_nth(self, index: int = 0) -> Any:
if not 0 <= index < len(self):
raise IndexError("list index out of range.")

assert self.head is not None and self.tail is not None
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
Expand All@@ -137,7 +138,8 @@ def delete_nth(self, index: int = 0) -> Any:
for _ in range(index - 1):
assert temp is not None
temp = temp.next
assert temp is not None and temp.next is not None
assert temp is not None
assert temp.next is not None
delete_node = temp.next
temp.next = temp.next.next
if index == len(self) - 1: # Delete at tail
Expand Down
3 changes: 2 additions & 1 deletion digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,8 @@ def test_median_filter():

def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
assert grad.any()
assert theta.any()


def test_sepia():
Expand Down
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('^' + ".*" + ' Add Ruff rules for pandas-vet and pytest-style by cclauss · Pull Request #10281 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.6.0
hooks:
- id: mypy
args:
Expand Down
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -532,6 +532,7 @@
* [Logistic Regression](machine_learning/logistic_regression.py)
* Loss Functions
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
* [Mfcc](machine_learning/mfcc.py)
Expand Down
6 changes: 4 additions & 2 deletions blockchain/diophantine_equation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
(1, -2, 3)

"""
assert a >= 0 and b >= 0
assert a >= 0
assert b >= 0

if b == 0:
d, x, y = a, 1, 0
Expand All@@ -92,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
x = q
y = p - q * (a // b)

assert a % d == 0 and b % d == 0
assert a % d == 0
assert b % d == 0
assert d == a * x + b * y

return (d, x, y)
Expand Down
18 changes: 12 additions & 6 deletions ciphers/xor_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,7 +38,8 @@ def encrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -56,7 +57,8 @@ def decrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
assert isinstance(key, int)
assert isinstance(content, list)

key = key or self.__key or 1

Expand All@@ -74,7 +76,8 @@ def encrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -99,7 +102,8 @@ def decrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -125,7 +129,8 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
Expand All@@ -148,7 +153,8 @@ def decrypt_file(self, file: str, key: int) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,8 @@ def decimal_to_hexadecimal(decimal: float) -> str:
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
assert isinstance(decimal, (int, float))
assert decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
Expand Down
28 changes: 15 additions & 13 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import unittest
from collections.abc import Iterator

import pytest


class Node:
def __init__(self, label: int, parent: Node | None) -> None:
Expand DownExpand Up@@ -78,7 +80,7 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
node.right = self._put(node.right, label, node)
else:
msg = f"Node with label {label} already exists"
raise Exception(msg)
raise ValueError(msg)

return node

Expand All@@ -95,14 +97,14 @@ def search(self, label: int) -> Node:
>>> node = t.search(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
return self._search(self.root, label)

def _search(self, node: Node | None, label: int) -> Node:
if node is None:
msg = f"Node with label {label} does not exist"
raise Exception(msg)
raise ValueError(msg)
else:
if label < node.label:
node = self._search(node.left, label)
Expand All@@ -124,7 +126,7 @@ def remove(self, label: int) -> None:
>>> t.remove(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
node = self.search(label)
if node.right and node.left:
Expand DownExpand Up@@ -179,7 +181,7 @@ def exists(self, label: int) -> bool:
try:
self.search(label)
return True
except Exception:
except ValueError:
return False

def get_max_label(self) -> int:
Expand All@@ -190,15 +192,15 @@ def get_max_label(self) -> int:
>>> t.get_max_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.right is not None:
Expand All@@ -214,15 +216,15 @@ def get_min_label(self) -> int:
>>> t.get_min_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.left is not None:
Expand DownExpand Up@@ -359,7 +361,7 @@ def test_put(self) -> None:
assert t.root.left.left.parent == t.root.left
assert t.root.left.left.label == 1

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.put(1)

def test_search(self) -> None:
Expand All@@ -371,7 +373,7 @@ def test_search(self) -> None:
node = t.search(13)
assert node.label == 13

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.search(2)

def test_remove(self) -> None:
Expand DownExpand Up@@ -517,7 +519,7 @@ def test_get_max_label(self) -> None:
assert t.get_max_label() == 14

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_max_label()

def test_get_min_label(self) -> None:
Expand All@@ -526,7 +528,7 @@ def test_get_min_label(self) -> None:
assert t.get_min_label() == 1

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_min_label()

def test_inorder_traversal(self) -> None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/hashing/tests/test_hash_map.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,14 +65,14 @@ def _run_operation(obj, fun, *args):

@pytest.mark.parametrize(
"operations",
(
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
Expand Down
6 changes: 4 additions & 2 deletions data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,7 +124,8 @@ def delete_nth(self, index: int = 0) -> Any:
if not 0 <= index < len(self):
raise IndexError("list index out of range.")

assert self.head is not None and self.tail is not None
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
Expand All@@ -137,7 +138,8 @@ def delete_nth(self, index: int = 0) -> Any:
for _ in range(index - 1):
assert temp is not None
temp = temp.next
assert temp is not None and temp.next is not None
assert temp is not None
assert temp.next is not None
delete_node = temp.next
temp.next = temp.next.next
if index == len(self) - 1: # Delete at tail
Expand Down
3 changes: 2 additions & 1 deletion digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,8 @@ def test_median_filter():

def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
assert grad.any()
assert theta.any()


def test_sepia():
Expand Down
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); } })(); })(); Add Ruff rules for pandas-vet and pytest-style by cclauss · Pull Request #10281 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.6.0
hooks:
- id: mypy
args:
Expand Down
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -532,6 +532,7 @@
* [Logistic Regression](machine_learning/logistic_regression.py)
* Loss Functions
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
* [Mfcc](machine_learning/mfcc.py)
Expand Down
6 changes: 4 additions & 2 deletions blockchain/diophantine_equation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
(1, -2, 3)

"""
assert a >= 0 and b >= 0
assert a >= 0
assert b >= 0

if b == 0:
d, x, y = a, 1, 0
Expand All@@ -92,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
x = q
y = p - q * (a // b)

assert a % d == 0 and b % d == 0
assert a % d == 0
assert b % d == 0
assert d == a * x + b * y

return (d, x, y)
Expand Down
18 changes: 12 additions & 6 deletions ciphers/xor_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,7 +38,8 @@ def encrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -56,7 +57,8 @@ def decrypt(self, content: str, key: int) -> list[str]:
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
assert isinstance(key, int)
assert isinstance(content, list)

key = key or self.__key or 1

Expand All@@ -74,7 +76,8 @@ def encrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -99,7 +102,8 @@ def decrypt_string(self, content: str, key: int = 0) -> str:
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
assert isinstance(key, int)
assert isinstance(content, str)

key = key or self.__key or 1

Expand All@@ -125,7 +129,8 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
Expand All@@ -148,7 +153,8 @@ def decrypt_file(self, file: str, key: int) -> bool:
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
assert isinstance(file, str)
assert isinstance(key, int)

try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,8 @@ def decimal_to_hexadecimal(decimal: float) -> str:
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
assert isinstance(decimal, (int, float))
assert decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
Expand Down
28 changes: 15 additions & 13 deletions data_structures/binary_tree/binary_search_tree_recursive.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import unittest
from collections.abc import Iterator

import pytest


class Node:
def __init__(self, label: int, parent: Node | None) -> None:
Expand DownExpand Up@@ -78,7 +80,7 @@ def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Nod
node.right = self._put(node.right, label, node)
else:
msg = f"Node with label {label} already exists"
raise Exception(msg)
raise ValueError(msg)

return node

Expand All@@ -95,14 +97,14 @@ def search(self, label: int) -> Node:
>>> node = t.search(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
return self._search(self.root, label)

def _search(self, node: Node | None, label: int) -> Node:
if node is None:
msg = f"Node with label {label} does not exist"
raise Exception(msg)
raise ValueError(msg)
else:
if label < node.label:
node = self._search(node.left, label)
Expand All@@ -124,7 +126,7 @@ def remove(self, label: int) -> None:
>>> t.remove(3)
Traceback (most recent call last):
...
Exception: Node with label 3 does not exist
ValueError: Node with label 3 does not exist
"""
node = self.search(label)
if node.right and node.left:
Expand DownExpand Up@@ -179,7 +181,7 @@ def exists(self, label: int) -> bool:
try:
self.search(label)
return True
except Exception:
except ValueError:
return False

def get_max_label(self) -> int:
Expand All@@ -190,15 +192,15 @@ def get_max_label(self) -> int:
>>> t.get_max_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.right is not None:
Expand All@@ -214,15 +216,15 @@ def get_min_label(self) -> int:
>>> t.get_min_label()
Traceback (most recent call last):
...
Exception: Binary search tree is empty
ValueError: Binary search tree is empty

>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
if self.root is None:
raise Exception("Binary search tree is empty")
raise ValueError("Binary search tree is empty")

node = self.root
while node.left is not None:
Expand DownExpand Up@@ -359,7 +361,7 @@ def test_put(self) -> None:
assert t.root.left.left.parent == t.root.left
assert t.root.left.left.label == 1

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.put(1)

def test_search(self) -> None:
Expand All@@ -371,7 +373,7 @@ def test_search(self) -> None:
node = t.search(13)
assert node.label == 13

with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.search(2)

def test_remove(self) -> None:
Expand DownExpand Up@@ -517,7 +519,7 @@ def test_get_max_label(self) -> None:
assert t.get_max_label() == 14

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_max_label()

def test_get_min_label(self) -> None:
Expand All@@ -526,7 +528,7 @@ def test_get_min_label(self) -> None:
assert t.get_min_label() == 1

t.empty()
with self.assertRaises(Exception): # noqa: B017
with pytest.raises(ValueError):
t.get_min_label()

def test_inorder_traversal(self) -> None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/hashing/tests/test_hash_map.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,14 +65,14 @@ def _run_operation(obj, fun, *args):

@pytest.mark.parametrize(
"operations",
(
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
Expand Down
6 changes: 4 additions & 2 deletions data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,7 +124,8 @@ def delete_nth(self, index: int = 0) -> Any:
if not 0 <= index < len(self):
raise IndexError("list index out of range.")

assert self.head is not None and self.tail is not None
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
Expand All@@ -137,7 +138,8 @@ def delete_nth(self, index: int = 0) -> Any:
for _ in range(index - 1):
assert temp is not None
temp = temp.next
assert temp is not None and temp.next is not None
assert temp is not None
assert temp.next is not None
delete_node = temp.next
temp.next = temp.next.next
if index == len(self) - 1: # Delete at tail
Expand Down
3 changes: 2 additions & 1 deletion digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,8 @@ def test_median_filter():

def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
assert grad.any()
assert theta.any()


def test_sepia():
Expand Down
Loading