Skip to content

Instantly share code, notes, and snippets.

@eugena
Created October 9, 2017 08:53
Show Gist options
  • Save eugena/a5968264bbcfd2025a45a8d2eec1115d to your computer and use it in GitHub Desktop.
Save eugena/a5968264bbcfd2025a45a8d2eec1115d to your computer and use it in GitHub Desktop.
Trie with End marker
class Trie(object):
"""
Trie with End marker
"""
END = '_end_'
current = dict()
def add(self, word):
"""
Adds a word to Trie
"""
current = self.current
for letter in word:
current = current.setdefault(letter, {})
current[self.END] = self.END
def find(self, word, full=False):
"""
Finds a prefix in Trie depending on full flag
"""
current = self.current
for letter in word:
if letter in current:
current = current[letter]
else:
return False
else:
if not full:
if self.END in current:
return True
else:
return False
else:
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment