Created
January 30, 2019 19:01
-
-
Save tonyfabeen/63c304f4bcaa7fd48e2f9786e3a44c5b to your computer and use it in GitHub Desktop.
Trie Data Structure in Python
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 Node(): | |
def __init__(self): | |
self.children = {} | |
self.last = False | |
def __str__(self): | |
str(self.children.keys()) | |
class Trie(): | |
def __init__(self): | |
self.root = Node() | |
def insert(self, word): | |
current = self.root | |
for char in list(word): | |
if not char in current.children: | |
current.children[char] = Node() | |
current = current.children[char] | |
current.last = True | |
def search(self, chars): | |
current = self.root | |
for char in list(chars): | |
if not char in current.children: | |
return False | |
current = current.children[char] | |
return True | |
word = 'casaco' | |
trie = Trie() | |
def test_insert(): | |
trie.insert(word) | |
assert trie.root.children['c'] .children['a'].children['s'].children['a'].children['c'].children['o'] != None | |
def test_search(): | |
trie.insert(word) | |
assert trie.search('casa') | |
assert trie.search('cas') | |
assert trie.search('casaco') | |
assert not trie.search('tonho') | |
assert not trie.search('jirimum') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment