Skip to content

Instantly share code, notes, and snippets.

@kperath
Last active April 23, 2023 19:18
Show Gist options
  • Select an option

  • Save kperath/2ad1857b8e94a0142e98bf43d230d291 to your computer and use it in GitHub Desktop.

Select an option

Save kperath/2ad1857b8e94a0142e98bf43d230d291 to your computer and use it in GitHub Desktop.
Python Trie class - nicer than using just a map and $
class TrieNode:
def __init__(self):
self.children = {}
self.ref = 0 # number of references (ie. size of each map)
self.end = False
def add_word(self, word):
node = self
node.ref += 1
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.ref += 1
node.end = True
def search(self, word):
node = self
for c in word:
if c not in node.children:
return False
node = node.children[c]
return node.end
def remove_word(self, word):
node = self
node.ref -= 1
for c in word:
# note: could add early exit here is node.ref == 0
node = node.children[c]
node.ref -= 1
node.end = False # ex. ABC, ABC, ABCD don't want to add ABC twice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment