Skip to content

Instantly share code, notes, and snippets.

@scriptpapi
Forked from zshihang/trie.py
Last active May 20, 2018 03:51
Show Gist options
  • Save scriptpapi/24a1f388a150369d7f7ef7586a1ee01f to your computer and use it in GitHub Desktop.
Save scriptpapi/24a1f388a150369d7f7ef7586a1ee01f to your computer and use it in GitHub Desktop.
A simple Python Trie data structure implementation
# A simple Trie implementation
class Node:
def __init__(self):
self.children = dict()
self.count = 0
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
curr = self.root
for i in range(len(word)):
curr = curr.children.setdefault(i, Node())
curr.count += 1
def find(self, word):
curr = self.root
for i in word:
if i in curr.children:
curr = curr.children[i]
else:
raise ValueError("Not found")
if curr.count > 0:
return True
else:
raise ValueError("Not found")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment