Skip to content

Instantly share code, notes, and snippets.

@addie
Created December 17, 2015 07:33
Show Gist options
  • Save addie/2559d3c054edf3d22d12 to your computer and use it in GitHub Desktop.
Save addie/2559d3c054edf3d22d12 to your computer and use it in GitHub Desktop.
This is my naive implementation of a Trie data structure using an array to store the children
#!/usr/bin/env python3
class TrieNode:
""" Node storing character and array of children
nodes and is_terminal boolean """
def __init__(self, char=None, children=None, is_terminal=False):
self.char = char
self.children = [0 for x in range(128)]
self.is_terminal = is_terminal
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
self.insert_helper(self.root, word)
return
def insert_helper(self, node, word):
first_letter = ord(word[0])
remaining_letters = word[1:]
if not node.children[first_letter]:
new_node = TrieNode(first_letter)
node.children[first_letter] = new_node
self.insert_helper(node, word)
else:
next_node = node.children[first_letter]
if len(remaining_letters) == 0:
node.is_terminal = True
return
node.is_terminal = False
return self.insert_helper(next_node, remaining_letters)
def search(self, word):
if len(word) == 0:
return False
return self.search_helper(self.root, word)
def search_helper(self, node, word):
first_letter = ord(word[0])
remaining_letters = word[1:]
if not node.children[first_letter]:
return False
else:
next_node = node.children[first_letter]
if len(remaining_letters) == 0:
return node.is_terminal
return self.search_helper(next_node, remaining_letters)
def starts_with(self, word):
if len(word) == 0:
return False
return self.starts_with_helper(self.root, word)
def starts_with_helper(self, node, word):
first_letter = ord(word[0])
remaining_letters = word[1:]
if not node.children[first_letter]:
return False
else:
if len(remaining_letters) == 0:
return True
next_node = node.children[first_letter]
return self.starts_with_helper(next_node, remaining_letters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment