mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-21 16:52:05 +00:00
Create autocomplete_using_trie.py (#1406)
* Create autocomplete_using_trie.py The program aims to design a trie implementation for autocomplete which is easy to understand and ready to run. * Removed unused import * Updated the list value * Update autocomplete_using_trie.py * Run the code through Black and add doctest
This commit is contained in:
parent
38d7e7073a
commit
313a043107
64
other/autocomplete_using_trie.py
Normal file
64
other/autocomplete_using_trie.py
Normal file
|
@ -0,0 +1,64 @@
|
||||||
|
END = "#"
|
||||||
|
|
||||||
|
|
||||||
|
class Trie:
|
||||||
|
def __init__(self):
|
||||||
|
self._trie = {}
|
||||||
|
|
||||||
|
def insert_word(self, text):
|
||||||
|
trie = self._trie
|
||||||
|
for char in text:
|
||||||
|
if char not in trie:
|
||||||
|
trie[char] = {}
|
||||||
|
trie = trie[char]
|
||||||
|
trie[END] = True
|
||||||
|
|
||||||
|
def find_word(self, prefix):
|
||||||
|
trie = self._trie
|
||||||
|
for char in prefix:
|
||||||
|
if char in trie:
|
||||||
|
trie = trie[char]
|
||||||
|
else:
|
||||||
|
return []
|
||||||
|
return self._elements(trie)
|
||||||
|
|
||||||
|
def _elements(self, d):
|
||||||
|
result = []
|
||||||
|
for c, v in d.items():
|
||||||
|
if c == END:
|
||||||
|
subresult = [" "]
|
||||||
|
else:
|
||||||
|
subresult = [c + s for s in self._elements(v)]
|
||||||
|
result.extend(subresult)
|
||||||
|
return tuple(result)
|
||||||
|
|
||||||
|
|
||||||
|
trie = Trie()
|
||||||
|
words = ("depart", "detergent", "daring", "dog", "deer", "deal")
|
||||||
|
for word in words:
|
||||||
|
trie.insert_word(word)
|
||||||
|
|
||||||
|
|
||||||
|
def autocomplete_using_trie(s):
|
||||||
|
"""
|
||||||
|
>>> trie = Trie()
|
||||||
|
>>> for word in words:
|
||||||
|
... trie.insert_word(word)
|
||||||
|
...
|
||||||
|
>>> matches = autocomplete_using_trie("de")
|
||||||
|
|
||||||
|
"detergent " in matches
|
||||||
|
True
|
||||||
|
"dog " in matches
|
||||||
|
False
|
||||||
|
"""
|
||||||
|
suffixes = trie.find_word(s)
|
||||||
|
return tuple(s + w for w in suffixes)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print(autocomplete_using_trie("de"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
Loading…
Reference in New Issue
Block a user