MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / Trie

Class Trie

strings/autocomplete_using_trie.py:6–32  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4
5
6class Trie:
7 def __init__(self) -> None:
8 self._trie: dict = {}
9
10 def insert_word(self, text: str) -> None:
11 trie = self._trie
12 for char in text:
13 if char not in trie:
14 trie[char] = {}
15 trie = trie[char]
16 trie[END] = True
17
18 def find_word(self, prefix: str) -> tuple | list:
19 trie = self._trie
20 for char in prefix:
21 if char in trie:
22 trie = trie[char]
23 else:
24 return []
25 return self._elements(trie)
26
27 def _elements(self, d: dict) -> tuple:
28 result = []
29 for c, v in d.items():
30 sub_result = [" "] if c == END else [(c + s) for s in self._elements(v)]
31 result.extend(sub_result)
32 return tuple(result)
33
34
35trie = Trie()

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected