Last active
June 12, 2019 18:48
-
-
Save WhiskersReneeWe/072d057163178f7af66b1d424abb0634 to your computer and use it in GitHub Desktop.
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
class TrieNode: | |
def __init__(self): | |
## Initialize this node in the Trie | |
self.children = {} | |
self.is_word = False | |
def insert(self, char): | |
## Add a child node in this Trie | |
if char not in self.children: | |
self.children[char] = TrieNode() | |
def suffixes(self, suffix = ''): | |
## Recursive function that collects the suffix for | |
## all complete words below this point | |
result = [] | |
if self.is_word: | |
result.append(suffix) | |
for char, node in self.children.items(): | |
# this node is the end of word and a leaf node itself | |
if node.is_word and not node.children: | |
result.append(suffix + char) | |
if node.is_word and node.children: | |
result.append(suffix + char) | |
node.suffixes(suffix + char) | |
return result | |
## The Trie itself containing the root node and insert/find functions | |
class Trie: | |
def __init__(self): | |
## Initialize this Trie (add a root node) | |
self.root = TrieNode() | |
def insert(self, word): | |
## Add a word to the Trie | |
curr = self.root | |
for char in word: | |
if char not in curr.children: | |
curr.children[char] = TrieNode() | |
curr = curr.children[char] | |
curr.is_word = True | |
def find(self, prefix): | |
## Find the Trie node that represents this prefix | |
curr = self.root | |
if len(curr.children) == 0: | |
return False | |
for char in prefix: | |
if char not in curr.children: | |
return False | |
curr = curr.children[char] | |
return curr | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment