Created
January 18, 2022 18:25
-
-
Save sssemil/87c94e48f63243107d2032d8ccb24269 to your computer and use it in GitHub Desktop.
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 TrieNode: | |
def __init__(self): | |
self.value = "_" | |
self.children = {} | |
def insert(self, str): | |
if not str: | |
c = "" | |
self.children[c] = TrieNode() | |
self.children[c].value = c | |
return | |
c, *rstr = str | |
if c not in self.children.keys(): | |
self.children[c] = TrieNode() | |
self.children[c].value = c | |
self.children[c].insert(rstr) | |
def find_node(self, str): | |
if not str: | |
return self | |
c, *rstr = str | |
if c in self.children.keys(): | |
return self.children[c].find_node(rstr) | |
def unpack(self, prefix, strs): | |
if not self.children: | |
strs.append(prefix) | |
for (char, node) in self.children.items(): | |
node.unpack(prefix + char, strs) | |
def autocomplete(self, str): | |
strs = [] | |
subroot = self.find_node(str) | |
if subroot: | |
subroot.unpack(str, strs) | |
return strs | |
def _print(self, depth, row): | |
if not row: | |
padding = "" | |
start = "" | |
else: | |
padding = "_" * depth | |
start = "\n" | |
print(F"{start}{padding}{self.value}", end="") | |
for i, (char, node) in enumerate(self.children.items()): | |
node._print(depth + 1, i) | |
def print(self): | |
self._print(0, 0) | |
print() | |
root = TrieNode() | |
root.insert("hello") | |
root.insert("world") | |
root.insert("worlds") | |
root.insert("worldss") | |
root.insert("human") | |
root.insert("bruv") | |
root.insert("boyyyyy") | |
root.insert("where are you") | |
root.print() | |
autocomplete = root.autocomplete("w") | |
if autocomplete: | |
print(autocomplete) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment