Created
December 3, 2018 15:49
-
-
Save rupalbarman/0c9ebadec967e7f241a7af29fbd7d702 to your computer and use it in GitHub Desktop.
Trie implementation basic
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 Trie(object): | |
def __init__(self): | |
self.data = [None for _ in range(26)] | |
self.count = 0 | |
self.is_end = False | |
def __repr__(self): | |
node_data = (lambda x : (1, x.count, x.is_end) if x is not None else 0) | |
return str([node_data(x) for x in self.data]) | |
def add(t, word): | |
while len(word) > 0: | |
c_idx = ord(word[0]) - ord('a') | |
if t.data[c_idx] is None: | |
t.data[c_idx] = Trie() | |
t.data[c_idx].count += 1 | |
t = t.data[c_idx] | |
word = word[1:] | |
t.is_end = True | |
def find(t, word): | |
while len(word) > 0: | |
c_idx = ord(word[0]) - ord('a') | |
if t.data[c_idx] is None: | |
return t.count | |
else: | |
t = t.data[c_idx] | |
word = word[1:] | |
return t.count | |
def show(t): | |
print(t) | |
for _ in t.data: | |
if _ is not None: | |
show(_) | |
def main(): | |
t = Trie() | |
for _ in range(int(input().strip())): | |
cmd = input().strip().split(' ') | |
if cmd[0] == 'add': | |
add(t, cmd[1]) | |
elif cmd[0] == 'find': | |
print(find(t, cmd[1])) | |
elif cmd[0] == 'show': | |
show(t) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment