Skip to content

Instantly share code, notes, and snippets.

@danielpyon
Last active August 20, 2022 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpyon/7c33892780198f3f91e2f0a82b61245e to your computer and use it in GitHub Desktop.
Save danielpyon/7c33892780198f3f91e2f0a82b61245e to your computer and use it in GitHub Desktop.
simple trie implementation
# simple trie implementation
class Trie:
class Node:
def __init__(self, data=None, end=False):
self.data = data
self.children = dict()
# is this the end of a word?
self.end = end
def __str__(self):
return str(self.children)
def __repr__(self):
return str(self)
def add_child(self, node):
self.children[node.data] = node
def __init__(self):
self.root = Trie.Node()
def __contains__(self, string):
curr = self.root
for i in range(len(string)):
if string[i] in curr.children:
curr = curr.children[string[i]]
else:
return False
return True
def __str__(self):
return str(self.root)
def __repr__(self):
return str(self)
def startswith(self, string):
curr = self.root
for i in range(len(string)):
if string[i] in curr.children:
curr = curr.children[string[i]]
else:
return set()
ret = set()
def traverse_children(node, current_string):
if node.end:
ret.add(current_string)
return
for child in node.children.keys():
traverse_children(node.children[child], current_string + child)
traverse_children(curr, string)
return ret
def add(self, string):
curr = self.root
for i in range(len(string)):
if string[i] in curr.children:
curr = curr.children[string[i]]
else:
break
for j in range(i, len(string)):
end = j == len(string) - 1
curr.add_child(Trie.Node(string[j], end=end))
curr = curr.children[string[j]]
if __name__ == '__main__':
t = Trie()
t.add('CAR')
t.add('CAT')
t.add('COB')
print(t)
print('COB' in t)
print('COBD' in t)
print(t.startswith('C'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment