I've been working on implementing a Trie in Python for educational purposes. I tried implementing one using dictionaries and I was successful; find below my attempt at implementing a trie using lists alone.
The structure of a trie with the words in
, inn
, inner
, innerr
would be as follows :-
[['i', [['n', [['n', [['e', [['r', [['r', [], 'end']], 'end']]]], 'end']], 'end']]]]
where end
indicates the end of a word.
class TrieException(Exception):
pass
def add_word(word, trie):
END = "end"
if word == '':
raise TrieException("word empty")
prev = None
branch = trie
for i, c in enumerate(word):
found = False
for each in branch:
if each[0] == c:
if i == len(word)-1:
if len(each) > 2:
raise TrieException("Word already present")
else:
each.append(END)
prev = branch
branch = each[1]
found = True
break
if not found:
nb = []
if i == len(word)-1:
branch.append([c, nb, END])
else:
branch.append([c, nb])
branch = nb
def search_word(word, trie):
if word == '':
raise TrieException("empty word")
branch = trie
for i, c in enumerate(word):
found = False
for each in branch:
if each[0] == c:
found = True
branch = each[1]
if i == len(word)-1:
if len(each) <= 2:
raise TrieException("Word not found")
break
if not found:
raise TrieException("Word not found")
Do you have any suggestions on how I do this in a more cleaner fashion?