Hey, this is my first post here! Therefore, I am trying to implement a trie tree using a list in Python, however I have to face some difficulties. This is my code:
trie_root = []
list = ['to','toe']
for word in list:
if word == "":
continue
else:
cur_node = trie_root
for letter in word:
if len(cur_node)<1:
x=[letter]
cur_node.append(x)
cur_node=x
else:
for i in cur_node:
if letter == i[0]:
x=[i[0:]]
cur_node=x
break
else:
x=[letter]
cur_node.append(x)
cur_node = x
break
cur_node.append('$')
print(trie_root)
However, when I print trie_root, the output is [['t', ['o', '$']]]
Where is the "e" missing from the "toe" on the output? How to add it? However, if my list contains words starting with different letters, for example "jar" and "toe", it gives the correct conclusion: [['j', ['a', ['r', '$']]], ['t', ['o', ['e', '$']]]]
Thanks for reading!
source
share