-
-
Save scriptpapi/24a1f388a150369d7f7ef7586a1ee01f to your computer and use it in GitHub Desktop.
A simple Python Trie data structure implementation
This file contains hidden or 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
# 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