Skip to content

Instantly share code, notes, and snippets.

@pattoM
Created November 7, 2020 22:47
Show Gist options
  • Save pattoM/f76913512fb5f01c45c156758482b46f to your computer and use it in GitHub Desktop.
Save pattoM/f76913512fb5f01c45c156758482b46f to your computer and use it in GitHub Desktop.
#using dictionaries
class TrieDict:
def __init__(self):
self.hub = {"*":{}}
def add_new(self,word):
#set head to hub
cur_node = self.hub["*"]
#loop through word
for c in word:
#check if c in hub keys, if not add
if c not in cur_node:
cur_node[c] = {}
cur_node = cur_node[c]
else:
cur_node = cur_node[c]
#at end, add a *
cur_node["*"] = {}
print(self.hub)
def check_present(self, word):
cur_node = self.hub["*"]
for c in word:
if c in cur_node:
cur_node = cur_node[c]
else:
return False
#check for * denoting end
if "*" in cur_node:
return True
else:
return False
trie1 = TrieDict()
#add some
trie1.add_new("abacus")
trie1.add_new("abandon")
trie1.add_new("election")
#assertions of expected behavior
assert(trie1.check_present("abacus") == True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment