Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sleebapaul
Created February 9, 2020 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sleebapaul/4dad96ad8ab28c259727105d99c1c1fc to your computer and use it in GitHub Desktop.
Save sleebapaul/4dad96ad8ab28c259727105d99c1c1fc to your computer and use it in GitHub Desktop.
Adventures with Trie data structure
class Node():
def __init__(self, character):
self.letter = character
self.isEndOfWord = False
self.children = {}
class Trie:
def __init__(self):
"""
Initialize an empty Node as root.
"""
self.root = Node("")
def _getIndex(self, character):
return ord(character) - ord("a")
def insert(self, word):
"""
Inserts a word into the trie.
"""
cur = self.root
for letter in word:
idx = self._getIndex(letter)
if not cur.children.get(idx):
cur.children[idx] = Node(letter)
cur = cur.children[idx]
cur.isEndOfWord = True
def search(self, word):
"""
Returns if the word is in the trie.
"""
cur = self.root
for letter in word:
idx = self._getIndex(letter)
if not cur.children.get(idx):
return False
cur = cur.children[idx]
return cur and cur.isEndOfWord
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
cur = self.root
for letter in prefix:
idx = self._getIndex(letter)
if not cur.children.get(idx):
return False
cur = cur.children[idx]
return True
def delete(self, word):
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
cur = self.root
for letter in word[:-1]:
idx = self._getIndex(letter)
if not cur.children.get(idx):
return False
cur = cur.children[idx]
lastIndex = self._getIndex(word[-1])
if cur.children.get(lastIndex):
del cur.children[lastIndex]
return True
return False
if __name__ == "__main__":
trie = Trie()
print(trie.insert("apple"))
print(trie.search("apple"))
print(trie.search("app"))
print(trie.startsWith("app"))
print(trie.insert("app"))
print(trie.search("app"))
print(trie.delete("app"))
print(trie.search("app"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment