Last active
November 16, 2016 04:12
-
-
Save tonyslowdown/73ee62dc4ec7e0d5873e6455f2d9f46c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 TrieNode: | |
def __init__(self): | |
"""Node objects within trie | |
""" | |
self.children = {} | |
self.is_word = False | |
class Trie: | |
def __init__(self): | |
self.root = TrieNode() | |
def insert(self, word): | |
""" | |
Inserts a word into the trie. | |
:type word: str | |
:rtype: void | |
""" | |
curr_node = self.root | |
for c in word: | |
try: | |
curr_node = curr_node.children[c] | |
except: | |
curr_node.children[c] = TrieNode() | |
curr_node = curr_node.children[c] | |
curr_node.is_word = True | |
def search(self, word): | |
""" | |
Returns if the word is in the trie. | |
:type word: str | |
:rtype: bool | |
""" | |
curr_node = self.root | |
for c in word: | |
try: | |
curr_node = curr_node.children[c] | |
except KeyError: | |
return False | |
return curr_node.is_word | |
def starts_with(self, prefix): | |
""" | |
Returns if there is any word in the trie | |
that starts with the given prefix. | |
:type prefix: str | |
:rtype: bool | |
""" | |
curr_node = self.root | |
for c in prefix: | |
try: | |
curr_node = curr_node.children[c] | |
except KeyError: | |
return False | |
return True | |
if __name__ == '__main__': | |
trie = Trie() | |
trie.insert("somestring") | |
trie.search("key") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment