Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

Exceptions are for exceptional (read 'rare','unexpected') edge cases

You are using exceptions as the default behaviour, this is not nice, instead functions should return values, remove TrieException("word not find") from search_word(word, trie) and instead return True if you find the word and False if you do not find it.

Confusing alias

branch = trie

You just confuse the reader, each thing should have one name only.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.