Trie Prefix Search And Autocomplete (Python)
Build a trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.
Code
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
self.freq = 0
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word, freq=1):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_word = True
node.freq += freq
def suggest(self, prefix, limit=5):
node = self.root
for ch in prefix:
node = node.children.get(ch)
if not node:
return []
results = []
def dfs(n, path):
if n.is_word:
results.append((path, n.freq))
for ch, child in n.children.items():
dfs(child, path + ch)
dfs(node, prefix)
results.sort(key=lambda x: -x[1])
return [w for w, _ in results[:limit]]Report a problem with this exampleOpens a pre-filled issue on GitHub.