Skip to content

Instantly share code, notes, and snippets.

@tonyslowdown
Created November 1, 2016 02:37
Show Gist options
  • Save tonyslowdown/adecd311dc414404c38dd17149aad666 to your computer and use it in GitHub Desktop.
Save tonyslowdown/adecd311dc414404c38dd17149aad666 to your computer and use it in GitHub Desktop.
Trie object in python using hash tables for keeping track of children
class Trie:
"""
Trie object will try to optimize by keeping unseen suffixes in a single node,
and then unravels those suffixes when the letters in the suffix are encountered
"""
class Node:
"""Each trie node"""
def __init__(self):
self.children = {}
self.count = 1
self.suffix = None
self.is_suffix = False
def set_suffix(self, suffix):
self.suffix = suffix
self.is_suffix = True
def unset_suffix(self):
_t = self.suffix
self.suffix = None
self.is_suffix = False
return _t
def __init__(self):
self.root = Trie.Node()
def add(self, value):
node = self.root
for i, c in enumerate(value):
# If the suffix is not in the trie already
# just add entire suffix in a single node
if c not in node.children:
# Create a suffix type of node, containing multiple characters
node.children[c] = Trie.Node()
node.children[c].set_suffix(value[i+1:])
return
elif node.children[c].is_suffix: # Reached a suffix node
# Unravel the suffix
_trie = Trie()
_trie.root = node.children[c]
_trie.add(node.children[c].unset_suffix())
node = node.children[c]
node.count += 1
def get_count(self, value):
node = self.root
for c in value:
# If suffix not in the trie
if c not in node.children:
return 0
elif node.children[c].is_suffix: # Reached a suffix node
# Unravel the suffix
_trie = Trie()
_trie.root = node.children[c]
_trie.add(node.children[c].unset_suffix())
node = node.children[c]
return node.count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment