Tries
104 / 170TriesLesson 1 of 4About 64 min
A tree where the path spells the word. Two fields per node and that is the whole structure.
This trie has no end-of-word flag and treats any successful walk as a word. Type the three values it prints.
class Node: def __init__(self): self.children = {} root = Node()for word in ["cart"]: node = root for ch in word: node = node.children.setdefault(ch, Node()) def contains(text): node = root for ch in text: if ch not in node.children: return False node = node.children[ch] return True print(contains("cart"), contains("car"), contains("cab"))A trie is given as nested dictionaries, where a # key marks the end of a stored word. count_words reports how many words the whole trie holds. count_with_prefix reports how many of them begin with a given prefix. longest_stored_prefix_of returns the longest stored word that is a prefix of the given text, or the empty string if there is none.
Tests
print(count_words(TRIE), count_words({}))print(count_with_prefix(TRIE, "ca"), count_with_prefix(TRIE, "do"), count_with_prefix(TRIE, "z"), count_with_prefix(TRIE, ""))print(longest_stored_prefix_of(TRIE, "cartoon"), longest_stored_prefix_of(TRIE, "carbon"), repr(longest_stored_prefix_of(TRIE, "zebra")))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.