Last active
August 17, 2017 16:53
-
-
Save borgwang/eaa6b50ab6368c21f15e92dd6d0b7532 to your computer and use it in GitHub Desktop.
trie tree demo
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(object): | |
def __init__(self): | |
self.children = dict() | |
self.is_word = False | |
class TrieTree(object): | |
def __init__(self): | |
self.root = TrieNode() | |
def insert(self, word): | |
node = self.root | |
for letter in word: | |
child = node.children.get(letter) | |
if child is None: | |
child = TrieNode() | |
node.children[letter] = child | |
node = child | |
node.is_word = True | |
def search(self, word): | |
ans = '' | |
node = self.root | |
for letter in word: | |
child = node.children.get(letter) | |
if child is None: | |
return False | |
ans += letter | |
if child.is_word: | |
print('contain word: %s' % ans) | |
node = child | |
return True | |
if __name__ == '__main__': | |
tree = TrieTree() | |
words = ['a', 'the', 'there', 'their', 'answser', 'any', 'bye', 'by'] | |
for w in words: | |
tree.insert(w) | |
print(tree.search('there')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment