Created
August 5, 2020 14:37
-
-
Save erjan/185b9dae6c569ba88876353fccf03e07 to your computer and use it in GitHub Desktop.
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: | |
def __init__(self): | |
self.endword = False | |
self.children = [None]*26 | |
def insert(self,word): | |
print() | |
curr = self | |
for c in word: | |
print('inserting %c' % c) | |
if curr.children[ ord(c) - ord('a')] == None: | |
print('inserting at ord(c) - ord(a): %d ' % (ord(c) - ord('a'))) | |
curr.children[ord(c) - ord('a')] = Trie() | |
curr = curr.children[ord(c) - ord('a')] | |
count = 0 | |
for x in curr.children: | |
print( str(count) + ' here ' + str(x)) | |
count+=1 | |
curr.endword = True | |
def print_trie(self,curr=None): | |
res = [] | |
if curr is None: | |
curr = self | |
if curr.children: | |
for c in curr.children: | |
if c.endword == False: | |
for el in self.print_trie(c): | |
res.append(c + el) | |
else: | |
res.append('') | |
return res | |
def search(self,word): | |
curr =self | |
for c in word: | |
curr = curr.children[ord(c) - ord('a')] | |
if curr == None: | |
return False | |
if curr.endword: | |
return True | |
return False | |
def startsWith(self,prefix): | |
curr = self | |
for c in prefix: | |
curr = curr.children[ord(c)-ord('a')] | |
if curr == None: | |
return False | |
return True | |
main = Trie() | |
main.insert('apple') | |
main.insert('app') | |
main.insert('appetit') | |
main.insert('apples') | |
main.insert('tea') | |
print('printing actual trie') | |
print(main.print_trie(main)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment