Skip to content

Instantly share code, notes, and snippets.

@onelharrison
Last active February 20, 2020 15:50
Show Gist options
  • Save onelharrison/cc912deaf2bd19995de5ce187ddf6345 to your computer and use it in GitHub Desktop.
Save onelharrison/cc912deaf2bd19995de5ce187ddf6345 to your computer and use it in GitHub Desktop.
Implementation of the Trie data structure
class TrieNode:
def __init__(self, char=None, children={}, terminal=False):
self.char = char
self.children = children
self.terminal = terminal
class Trie:
def __init__(self):
self.root = TrieNode()
def find_prefix(self, prefix):
trie_node = self.root
for char in map(str.lower, prefix):
if char not in trie_node.children:
return False, trie_node
trie_node = trie_node.children[char]
return True, trie_node
def find_word(self, word):
found_word_as_prefix, trie_node = self.find_prefix(word)
if found_word_as_prefix:
return trie_node.terminal == True
return False
def add_word(self, word):
trie_node = self.root
for char in map(str.lower, word):
if char not in trie_node.children:
trie_node.children[char] = TrieNode(char)
trie_node = trie_node.children[char]
trie_node.terminal = True
t = Trie()
t.add_word('hello')
t.add_word('high')
print(t.find_prefix('hell')[0]) # True
print(t.find_prefix('hi')[0]) # True
print(t.find_word('hi')) # False
t.add_word('hi')
print(t.find_word('hi')) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment