Adventures with Trie data structure
This file contains 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 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