Created
April 28, 2022 20:34
-
-
Save FedericoPonzi/26010c88f47dc8876a17890cc70b999b to your computer and use it in GitHub Desktop.
Tries in python
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 Trie: | |
def __init__(self): | |
self.children = {} | |
self.isTerminal = False | |
def setIsTerminal(self): | |
self.isTerminal = True | |
def insert(self, word: str) -> None: | |
head, tail = word[0], word[1:] | |
if head not in self.children: | |
self.children[head] = Trie() | |
if len(word) == 1: | |
self.children[head].setIsTerminal() | |
else: | |
self.children[head].insert(tail) | |
def search(self, word: str) -> bool: | |
head, tail = word[0], word[1:] | |
if len(word) == 1: | |
return head in self.children and self.children[head].isTerminal | |
return head in self.children and self.children[head].search(tail) | |
def startsWith(self, prefix: str) -> bool: | |
if len(prefix) == 0: | |
return True | |
head, tail = prefix[0], prefix[1:] | |
return head in self.children and self.children[head].startsWith(tail) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment