Skip to content

Trie implementation #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 10, 2017
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions data_structures/Trie/Trie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""
A Trie/Prefix Tree is a kind of search tree used to provide quick lookup
of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity
making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup
time making it an optimal approach when space is not an issue.

This implementation assumes the character $ is not in any of the words. This character is used in the implementation
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please find some way to achieve the desired result without setting a predefined character? An algorithm is supposed to consider all test cases in mind. Good job though!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, no prob! I'll work on it

to mark the end of a word.
"""


class TrieNode:
def __init__(self):
self.nodes = dict() # Mapping from char to TrieNode

def insert_many(self, words: [str]):
"""
Inserts a list of words into the Trie
:param words: list of string words
:return: None
"""
for word in words:
self.insert(word)

def insert(self, word: str):
"""
Inserts a word into the Trie
:param word: word to be inserted
:return: None
"""
word += '$'
curr = self
for char in word:
if char not in curr.nodes:
curr.nodes[char] = TrieNode()
curr = curr.nodes[char]

def find(self, word: str) -> bool:
"""
Tries to find word in a Trie
:param word: word to look for
:return: Returns True if word is found, False otherwise
"""
word += '$'
curr = self
for char in word:
if char not in curr.nodes:
return False
curr = curr.nodes[char]
return True


def print_words(node: TrieNode, word: str):
"""
Prints all the words in a Trie
:param node: root node of Trie
:param word: Word variable should be empty at start
:return: None
"""
if '$' in node.nodes:
print(word, end=' ')

for key, value in node.nodes.items():
print_words(value, word + key)


def test():
words = []
# Load words from text file into Trie
with open("../../other/Dictionary.txt", "r") as ins:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please switch this with a string sample? This would make it easier for the user to run and test the code. Thanks.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the sample I had in 9a52167 ok?

for line in ins:
words.append(line.strip().lower())
root = TrieNode()
root.insert_many(words)
# print_words(root, '')
assert root.find('bananas')
assert not root.find('bandanas')
assert not root.find('apps')
assert root.find('apple')

# test()
Empty file.