Hi,
I have a python question:
I found different python codes on the internet that create and search a trie at the same time (the trie created at run time), but, none of these codes search an existing trie and produce a list of possible matches, I tried to create a code based on those trie codes, so I can search an existing trie, but for some reason, it is not working for me.
Here is the code
class TrieNode:
def __init__(self):
# self.children is the existing trie
self.children = {'a': {'*': '*', 'p': {'p': {'l': {'e': {'*': '*'}}}}, 'n': {'g': {'l': {'e': {'*': '*'}}, 'e': {'l': {'*': '*'}}}}}, 'b': {'a': {'t': {'*': '*', 's': {'*': '*'}}}}}
def all_words(self, prefix):
if self.children[w] == "*":
yield prefix
print (self.children.items())
for letter, child in self.children.items():
yield from child.all_words(prefix + letter)
class Trie:
def __init__(self):
self.root = TrieNode()
def all_words_beginning_with_prefix(self, prefix):
cur = self.root
for c in prefix:
cur = cur.children.get(c)
if cur is None:
return # No words with given prefix
print (cur)
yield from cur.all_words(prefix)
trie = Trie()
print(list(trie.all_words_beginning_with_prefix('ap')))
Please review the code and advise on how I can create a method that searches an existing trie.
Thank you for your help