Skip to content

Instantly share code, notes, and snippets.

@erjan
Created August 5, 2020 14:37
Show Gist options
  • Save erjan/185b9dae6c569ba88876353fccf03e07 to your computer and use it in GitHub Desktop.
Save erjan/185b9dae6c569ba88876353fccf03e07 to your computer and use it in GitHub Desktop.
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