Skip to content

Instantly share code, notes, and snippets.

@FedericoPonzi
Created April 28, 2022 20:34
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 FedericoPonzi/26010c88f47dc8876a17890cc70b999b to your computer and use it in GitHub Desktop.
Save FedericoPonzi/26010c88f47dc8876a17890cc70b999b to your computer and use it in GitHub Desktop.
Tries in python
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