Skip to content

Commit 25302d5

Browse files
Refactor Trie documentation and improve type hints; fix formatting in docstring examples
1 parent 0cf706c commit 25302d5

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

data_structures/trie/trie.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
"""
22
Trie (Prefix Tree) Data Structure
33
4-
A Trie is a tree-like data structure that stores strings efficiently. Each node represents
5-
a character, and paths from root to leaf nodes form complete words.
4+
A Trie is a tree-like data structure that stores strings efficiently.
5+
Each node represents a character, and paths from root to leaf nodes form complete words.
66
77
Reference: https://en.wikipedia.org/wiki/Trie
88
@@ -26,8 +26,6 @@
2626
- Word games (Scrabble)
2727
"""
2828

29-
from typing import Dict
30-
3129

3230
class Node:
3331
"""Represents a single node in the Trie.
@@ -38,7 +36,7 @@ class Node:
3836
"""
3937

4038
def __init__(self):
41-
self.children: Dict[str, Node] = {} # Maps character to child Node
39+
self.children: dict[str, Node] = {} # Maps character to child Node
4240
self.is_end_of_word = False # True if node represents end of a valid word
4341

4442

@@ -334,12 +332,8 @@ def print_all_words(self) -> None:
334332
- If marked as end of word, print the current word
335333
- Recursively visit all children
336334
337-
Examples:
338-
>>> trie = Trie()
339-
>>> trie.insert("a")
340-
>>> trie.insert("b")
341-
>>> trie.print_all_words()
342-
a b
335+
Note:
336+
Output has a trailing space after the last word.
343337
"""
344338

345339
def _print_words(node: Node, current_word: str) -> None:
@@ -537,11 +531,15 @@ def _find_words(node: Node, current_word: str):
537531
print("-" * 60)
538532
trie.delete("apple")
539533
print(f" After deletion - searching 'apple': {trie.search('apple')}")
534+
app_exists = trie.search("application")
540535
print(
541-
f" Checking if 'application' still exists: {trie.search('application')} (should be True)"
536+
f" Checking if 'application' still exists: {app_exists} "
537+
"(should be True)"
542538
)
539+
app_prefix = trie.starts_with("app")
543540
print(
544-
f" Checking if prefix 'app' still matches: {trie.starts_with('app')} (should be True)"
541+
f" Checking if prefix 'app' still matches: {app_prefix} "
542+
"(should be True)"
545543
)
546544

547545
# Test 10: Verify final state

0 commit comments

Comments
 (0)