Skip to content

Instantly share code, notes, and snippets.

@tonyfabeen
Created January 30, 2019 19:01
Show Gist options
  • Save tonyfabeen/63c304f4bcaa7fd48e2f9786e3a44c5b to your computer and use it in GitHub Desktop.
Save tonyfabeen/63c304f4bcaa7fd48e2f9786e3a44c5b to your computer and use it in GitHub Desktop.
Trie Data Structure in Python
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