-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrie_node.py
More file actions
62 lines (47 loc) · 1.64 KB
/
trie_node.py
File metadata and controls
62 lines (47 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from typing import DefaultDict, Optional
from collections import defaultdict
class TrieNode:
def __init__(self):
# self.char = char
"""
Initializes a TrieNode instance.
A TrieNode contains a character and a dictionary of its children. It also contains a boolean indicating whether the node is the end of a word in the Trie.
Parameters:
None
Returns:
None
"""
self.children: DefaultDict[str, TrieNode] = defaultdict(TrieNode)
self.is_end = False
self.index: Optional[int] = None
def __repr__(self):
return f"TrieNode(children={self.children.items()}, index={self.index}, is_end={self.is_end})"
def insert(self, word: str, index: int):
"""
Inserts a word into the TrieNode.
Parameters:
word (str): The word to insert
index (int): The index of the word
Returns:
None
"""
curr = self
for char in word:
curr = curr.children[char]
curr.index = min(curr.index or float("inf"), index)
curr.is_end = True
def search_prefix(self, prefix: str) -> int:
"""
Searches for a prefix in the TrieNode.
Parameters:
prefix (str): The prefix to search for
Returns:
int: The index of the word if the prefix is found, -1 otherwise
"""
current = self
for char in prefix:
if char not in current.children:
return -1
# Traverse to the next node
current = current.children[char]
return current.index