Skip to content

Commit 30a34cd

Browse files
Fix all ruff linting errors
- Fix advanced_trie.py: - Replace deprecated typing.List/Dict/Set with built-in list/dict/set - Replace Optional[T] with T | None syntax - Remove unused imports (Set, re) - Fix line length issues - Convert else-if chains to elif - Remove f-string prefixes where no placeholders - Fix unused variable by prefixing with underscore - Fix bloom_filter.py: - Replace deprecated typing.List with built-in list - Replace Union[T, U] with T | U syntax - Remove unnecessary int() casting around math.ceil() - Remove f-string prefixes where no placeholders - Fix fenwick_tree.py: - Replace deprecated typing.List with built-in list - Fix exception f-string issues by assigning to variables first - Remove f-string prefixes where no placeholders - Fix segment_tree.py: - Replace deprecated typing.List with built-in list - Import Callable from collections.abc instead of typing - Fix Optional type annotations - Fix exception f-string issues by assigning to variables first - Remove f-string prefixes where no placeholders - Fix fft_cooley_tukey.py: - Replace deprecated typing.List/Tuple with built-in list/tuple - Fix long line by breaking into multiple lines - Remove unused typing.Optional import All files now pass ruff linting checks and follow modern Python type annotation standards.
1 parent 55186e8 commit 30a34cd

File tree

5 files changed

+93
-82
lines changed

5 files changed

+93
-82
lines changed

data_structures/advanced_trie.py

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,19 @@
1313
- Search: O(m) where m is the length of the string
1414
- Delete: O(m) where m is the length of the string
1515
- Prefix search: O(m + k) where m is prefix length, k is number of results
16-
Space Complexity: O(ALPHABET_SIZE * N * M) where N is number of strings, M is average length
16+
Space Complexity: O(ALPHABET_SIZE * N * M) where N is number of strings, M is avg length
1717
1818
Reference: https://en.wikipedia.org/wiki/Trie
1919
"""
2020

21-
from typing import List, Set, Optional, Dict, Any
22-
import re
21+
from typing import Optional, Any
2322

2423

2524
class TrieNode:
2625
"""Node in the Trie data structure."""
2726

2827
def __init__(self):
29-
self.children: Dict[str, "TrieNode"] = {}
28+
self.children: dict[str, TrieNode] = {}
3029
self.is_end_of_word: bool = False
3130
self.word_count: int = 0 # Number of words ending at this node
3231
self.prefix_count: int = 0 # Number of words with this prefix
@@ -171,7 +170,7 @@ def _delete_helper(self, node: TrieNode, word: str, index: int) -> bool:
171170
node.prefix_count -= 1
172171
return len(node.children) == 0 and not node.is_end_of_word
173172

174-
def _find_node(self, word: str) -> Optional[TrieNode]:
173+
def _find_node(self, word: str) -> TrieNode | None:
175174
"""
176175
Find the node corresponding to the given word.
177176
@@ -199,7 +198,7 @@ def _find_node(self, word: str) -> Optional[TrieNode]:
199198
node = node.children[char]
200199
return node
201200

202-
def get_all_words_with_prefix(self, prefix: str) -> List[str]:
201+
def get_all_words_with_prefix(self, prefix: str) -> list[str]:
203202
"""
204203
Get all words that start with the given prefix.
205204
@@ -226,7 +225,7 @@ def get_all_words_with_prefix(self, prefix: str) -> List[str]:
226225
return words
227226

228227
def _collect_words(
229-
self, node: TrieNode, current_word: str, words: List[str]
228+
self, node: TrieNode, current_word: str, words: list[str]
230229
) -> None:
231230
"""
232231
Collect all words from a given node.
@@ -251,7 +250,7 @@ def _collect_words(
251250
for char, child_node in node.children.items():
252251
self._collect_words(child_node, current_word + char, words)
253252

254-
def autocomplete(self, prefix: str, max_results: int = 10) -> List[str]:
253+
def autocomplete(self, prefix: str, max_results: int = 10) -> list[str]:
255254
"""
256255
Get autocomplete suggestions for the given prefix.
257256
@@ -341,7 +340,7 @@ def get_prefix_count(self, prefix: str) -> int:
341340
node = self._find_node(prefix)
342341
return node.prefix_count if node else 0
343342

344-
def pattern_search(self, pattern: str) -> List[str]:
343+
def pattern_search(self, pattern: str) -> list[str]:
345344
"""
346345
Search for words matching a pattern with wildcards.
347346
Supports '*' for any character and '?' for single character.
@@ -365,7 +364,7 @@ def pattern_search(self, pattern: str) -> List[str]:
365364
return words
366365

367366
def _pattern_search_helper(
368-
self, node: TrieNode, current_word: str, pattern: str, words: List[str]
367+
self, node: TrieNode, current_word: str, pattern: str, words: list[str]
369368
) -> None:
370369
"""Helper method for pattern search."""
371370
if not pattern:
@@ -389,14 +388,13 @@ def _pattern_search_helper(
389388
self._pattern_search_helper(
390389
child_node, current_word + child_char, remaining_pattern, words
391390
)
392-
else:
391+
elif char in node.children:
393392
# Match exact character
394-
if char in node.children:
395-
self._pattern_search_helper(
396-
node.children[char], current_word + char, remaining_pattern, words
397-
)
393+
self._pattern_search_helper(
394+
node.children[char], current_word + char, remaining_pattern, words
395+
)
398396

399-
def get_all_words(self) -> List[str]:
397+
def get_all_words(self) -> list[str]:
400398
"""
401399
Get all words in the trie.
402400
@@ -448,7 +446,7 @@ def _compress(self) -> None:
448446
def _compress_helper(self, node: TrieNode) -> None:
449447
"""Helper method for compression."""
450448
if len(node.children) == 1 and not node.is_end_of_word:
451-
child_char, child_node = next(iter(node.children.items()))
449+
_child_char, child_node = next(iter(node.children.items()))
452450
# Merge single child
453451
node.children = child_node.children
454452
node.is_end_of_word = child_node.is_end_of_word
@@ -477,22 +475,22 @@ def _compress_helper(self, node: TrieNode) -> None:
477475
print(f"\nTrie size: {len(trie)}")
478476

479477
# Search operations
480-
print(f"\nSearch operations:")
478+
print("\nSearch operations:")
481479
search_words = ["hello", "help", "xyz", "world"]
482480
for word in search_words:
483481
result = trie.search(word)
484482
print(f"'{word}': {'Found' if result else 'Not found'}")
485483

486484
# Prefix operations
487-
print(f"\nPrefix operations:")
485+
print("\nPrefix operations:")
488486
prefixes = ["hel", "wor", "xyz"]
489487
for prefix in prefixes:
490488
has_prefix = trie.starts_with(prefix)
491489
words_with_prefix = trie.get_all_words_with_prefix(prefix)
492490
print(f"Prefix '{prefix}': {has_prefix}, Words: {words_with_prefix}")
493491

494492
# Autocomplete
495-
print(f"\nAutocomplete:")
493+
print("\nAutocomplete:")
496494
autocomplete_prefixes = ["hel", "wor"]
497495
for prefix in autocomplete_prefixes:
498496
suggestions = trie.autocomplete(prefix, 3)
@@ -502,20 +500,20 @@ def _compress_helper(self, node: TrieNode) -> None:
502500
print(f"\nLongest common prefix: '{trie.longest_common_prefix()}'")
503501

504502
# Pattern search
505-
print(f"\nPattern search:")
503+
print("\nPattern search:")
506504
patterns = ["hel*", "wor?", "h*"]
507505
for pattern in patterns:
508506
matches = trie.pattern_search(pattern)
509507
print(f"Pattern '{pattern}': {matches}")
510508

511509
# Word counts
512-
print(f"\nWord counts:")
510+
print("\nWord counts:")
513511
trie.insert("hello") # Insert again
514512
print(f"'hello' count: {trie.get_word_count('hello')}")
515513
print(f"'hel' prefix count: {trie.get_prefix_count('hel')}")
516514

517515
# Delete operation
518-
print(f"\nDelete operation:")
516+
print("\nDelete operation:")
519517
print(f"Before delete - 'help' exists: {trie.search('help')}")
520518
trie.delete("help")
521519
print(f"After delete - 'help' exists: {trie.search('help')}")
@@ -524,4 +522,4 @@ def _compress_helper(self, node: TrieNode) -> None:
524522
# All words
525523
print(f"\nAll words in trie: {trie.get_all_words()}")
526524

527-
print(f"\nTrie implementation completed successfully!")
525+
print("\nTrie implementation completed successfully!")

data_structures/bloom_filter.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
import hashlib
1717
import math
18-
from typing import List, Union
18+
from typing import Union
1919

2020

2121
class BloomFilter:
@@ -62,15 +62,15 @@ def _calculate_size(self, n: int, p: float) -> int:
6262

6363
# m = -(n * ln(p)) / (ln(2)^2)
6464
size = -(n * math.log(p)) / (math.log(2) ** 2)
65-
return int(math.ceil(size))
65+
return math.ceil(size)
6666

6767
def _calculate_hash_functions(self, m: int, n: int) -> int:
6868
"""Calculate optimal number of hash functions."""
6969
# k = (m/n) * ln(2)
7070
k = (m / n) * math.log(2)
71-
return int(math.ceil(k))
71+
return math.ceil(k)
7272

73-
def _hash(self, item: Union[str, bytes], seed: int) -> int:
73+
def _hash(self, item: str | bytes, seed: int) -> int:
7474
"""
7575
Generate hash value for an item with given seed.
7676
@@ -100,7 +100,7 @@ def _hash(self, item: Union[str, bytes], seed: int) -> int:
100100

101101
return int(hash_obj.hexdigest(), 16) % self.size
102102

103-
def add(self, item: Union[str, bytes]) -> None:
103+
def add(self, item: str | bytes) -> None:
104104
"""
105105
Add an item to the Bloom Filter.
106106
@@ -119,7 +119,7 @@ def add(self, item: Union[str, bytes]) -> None:
119119

120120
self.count += 1
121121

122-
def contains(self, item: Union[str, bytes]) -> bool:
122+
def contains(self, item: str | bytes) -> bool:
123123
"""
124124
Check if an item might be in the Bloom Filter.
125125
@@ -193,7 +193,7 @@ def __len__(self) -> int:
193193
"""Return the number of items added to the filter."""
194194
return self.count
195195

196-
def __contains__(self, item: Union[str, bytes]) -> bool:
196+
def __contains__(self, item: str | bytes) -> bool:
197197
"""Support 'in' operator."""
198198
return self.contains(item)
199199

@@ -237,14 +237,14 @@ def _calculate_size(self, n: int, p: float) -> int:
237237
raise ValueError("False positive rate must be between 0 and 1")
238238

239239
size = -(n * math.log(p)) / (math.log(2) ** 2)
240-
return int(math.ceil(size))
240+
return math.ceil(size)
241241

242242
def _calculate_hash_functions(self, m: int, n: int) -> int:
243243
"""Calculate optimal number of hash functions."""
244244
k = (m / n) * math.log(2)
245-
return int(math.ceil(k))
245+
return math.ceil(k)
246246

247-
def _hash(self, item: Union[str, bytes], seed: int) -> int:
247+
def _hash(self, item: str | bytes, seed: int) -> int:
248248
"""Generate hash value for an item with given seed."""
249249
if isinstance(item, str):
250250
item = item.encode("utf-8")
@@ -264,7 +264,7 @@ def _hash(self, item: Union[str, bytes], seed: int) -> int:
264264

265265
return int(hash_obj.hexdigest(), 16) % self.size
266266

267-
def add(self, item: Union[str, bytes]) -> None:
267+
def add(self, item: str | bytes) -> None:
268268
"""Add an item to the Counting Bloom Filter."""
269269
for i in range(self.hash_functions):
270270
index = self._hash(item, i)
@@ -292,7 +292,7 @@ def remove(self, item: Union[str, bytes]) -> bool:
292292
self.count -= 1
293293
return True
294294

295-
def contains(self, item: Union[str, bytes]) -> bool:
295+
def contains(self, item: str | bytes) -> bool:
296296
"""Check if an item might be in the Counting Bloom Filter."""
297297
for i in range(self.hash_functions):
298298
index = self._hash(item, i)
@@ -316,7 +316,7 @@ def contains(self, item: Union[str, bytes]) -> bool:
316316
bf.add(item)
317317
print(f"Added: {item}")
318318

319-
print(f"\nBloom Filter Info:")
319+
print("\nBloom Filter Info:")
320320
print(f"Size: {bf.size}")
321321
print(f"Hash Functions: {bf.hash_functions}")
322322
print(f"Items Added: {len(bf)}")
@@ -325,13 +325,13 @@ def contains(self, item: Union[str, bytes]) -> bool:
325325

326326
# Test contains
327327
test_items = ["apple", "banana", "grape", "kiwi", "mango"]
328-
print(f"\nTesting items:")
328+
print("\nTesting items:")
329329
for item in test_items:
330330
result = bf.contains(item)
331331
print(f"'{item}': {'Found' if result else 'Not found'}")
332332

333333
# Counting Bloom Filter example
334-
print(f"\nCounting Bloom Filter Example")
334+
print("\nCounting Bloom Filter Example")
335335
print("=" * 50)
336336

337337
cbf = CountingBloomFilter(expected_items=100, false_positive_rate=0.05)
@@ -346,6 +346,6 @@ def contains(self, item: Union[str, bytes]) -> bool:
346346
print(f"Contains 'test2': {cbf.contains('test2')}")
347347
print(f"Contains 'test1': {cbf.contains('test1')}")
348348

349-
print(f"\nCounting Bloom Filter Info:")
349+
print("\nCounting Bloom Filter Info:")
350350
print(f"Items: {len(cbf)}")
351351
print(f"Load Factor: {cbf.get_load_factor():.3f}")

0 commit comments

Comments
 (0)