2022-05-13 05:55:53 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2019-10-20 08:40:40 +00:00
|
|
|
END = "#"
|
|
|
|
|
|
|
|
|
|
|
|
class Trie:
|
2022-05-13 05:55:53 +00:00
|
|
|
def __init__(self) -> None:
|
|
|
|
self._trie: dict = {}
|
2019-10-20 08:40:40 +00:00
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def insert_word(self, text: str) -> None:
|
2019-10-20 08:40:40 +00:00
|
|
|
trie = self._trie
|
|
|
|
for char in text:
|
|
|
|
if char not in trie:
|
|
|
|
trie[char] = {}
|
|
|
|
trie = trie[char]
|
|
|
|
trie[END] = True
|
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def find_word(self, prefix: str) -> tuple | list:
|
2019-10-20 08:40:40 +00:00
|
|
|
trie = self._trie
|
|
|
|
for char in prefix:
|
|
|
|
if char in trie:
|
|
|
|
trie = trie[char]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
return self._elements(trie)
|
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def _elements(self, d: dict) -> tuple:
|
2019-10-20 08:40:40 +00:00
|
|
|
result = []
|
|
|
|
for c, v in d.items():
|
|
|
|
if c == END:
|
2020-03-04 12:40:28 +00:00
|
|
|
sub_result = [" "]
|
2019-10-20 08:40:40 +00:00
|
|
|
else:
|
2020-03-04 12:40:28 +00:00
|
|
|
sub_result = [c + s for s in self._elements(v)]
|
|
|
|
result.extend(sub_result)
|
2019-10-20 08:40:40 +00:00
|
|
|
return tuple(result)
|
|
|
|
|
|
|
|
|
|
|
|
trie = Trie()
|
|
|
|
words = ("depart", "detergent", "daring", "dog", "deer", "deal")
|
|
|
|
for word in words:
|
|
|
|
trie.insert_word(word)
|
|
|
|
|
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def autocomplete_using_trie(string: str) -> tuple:
|
2019-10-20 08:40:40 +00:00
|
|
|
"""
|
|
|
|
>>> trie = Trie()
|
|
|
|
>>> for word in words:
|
|
|
|
... trie.insert_word(word)
|
|
|
|
...
|
|
|
|
>>> matches = autocomplete_using_trie("de")
|
2022-05-13 05:55:53 +00:00
|
|
|
>>> "detergent " in matches
|
2019-10-20 08:40:40 +00:00
|
|
|
True
|
2022-05-13 05:55:53 +00:00
|
|
|
>>> "dog " in matches
|
2019-10-20 08:40:40 +00:00
|
|
|
False
|
|
|
|
"""
|
2022-05-13 05:55:53 +00:00
|
|
|
suffixes = trie.find_word(string)
|
|
|
|
return tuple(string + word for word in suffixes)
|
2019-10-20 08:40:40 +00:00
|
|
|
|
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def main() -> None:
|
2019-10-20 08:40:40 +00:00
|
|
|
print(autocomplete_using_trie("de"))
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2022-05-13 05:55:53 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|
2019-10-20 08:40:40 +00:00
|
|
|
main()
|