Created
October 9, 2017 08:53
-
-
Save eugena/a5968264bbcfd2025a45a8d2eec1115d to your computer and use it in GitHub Desktop.
Trie with End marker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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