Last active
April 18, 2017 20:50
-
-
Save ozgurakan/2e0682e4282bfab496f0081c47a1f0df to your computer and use it in GitHub Desktop.
simple tries implementation
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
#!/bin/python3 | |
class Node(object): | |
def __init__(self, key=None, count=0): | |
self._key = key | |
self._count = count | |
self._children = dict() | |
@property | |
def children(self): | |
return self._children | |
@property | |
def key(self): | |
return self._key | |
@property | |
def count(self): | |
return self._count | |
@count.setter | |
def count(self, value): | |
self._count = value | |
def __str__(self): | |
return '{}:{}'.format(str(self.key), str(self.count)) | |
def add_child(self, node, count=0): | |
if not isinstance(node, Node): | |
key = node # using input as key | |
self._children[key] = Node(key, count) | |
else: | |
self._children[node.key] = node | |
class Tries(object): | |
def __init__(self): | |
self._root = Node() | |
def add(self, word): | |
current_node = self._root | |
for i in range(len(word)): | |
if word[i] not in current_node.children: | |
current_node.add_child(word[i]) | |
current_node = current_node.children[word[i]] | |
current_node.count += 1 | |
def graph(self, node=None, depth=0): | |
if not node: | |
node = self._root | |
print('_:_') | |
if len(node.children) > 0: | |
depth += 1 | |
for key, child in node.children.items(): | |
print('{}{}'.format(' '* depth, child)) | |
self.graph(child, depth) | |
def has(self, word): | |
current_node = self._root | |
for i in range(len(word)): | |
if word[i] in current_node.children: | |
current_node = current_node.children[word[i]] | |
else: | |
return False | |
return True | |
def count_children(self, node): | |
count = [node.count] | |
def counter(node): | |
for k in node.children: | |
count[0] += node.children[k].count | |
counter(node.children[k]) | |
counter(node) | |
return count[0] | |
def count(self, word): | |
count = 0 | |
current_node = self._root | |
for i in range(len(word)): | |
if word[i] in current_node.children: | |
current_node = current_node.children[word[i]] | |
else: | |
return 0 | |
return self.count_children(current_node) | |
if '__main__' == __name__: | |
trie = Tries() | |
trie.add('hello') | |
trie.add('hellos') | |
trie.add('hello') | |
trie.add('how') | |
trie.add('are') | |
trie.add('you') | |
trie.add('thank') | |
trie.add('thanks') | |
trie.add('you') | |
trie.graph() | |
print(trie.has('hel')) | |
print(trie.has('helo')) | |
print(trie.count('hello')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment