-
Notifications
You must be signed in to change notification settings - Fork 142
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add new trie algorithm with insert and search functions
- Loading branch information
1 parent
1ee7c81
commit 276bb2b
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
""" | ||
Implement a new trie algorithm with insert and search functions. | ||
Note: | ||
This implementation assumes all inputs consist of lowercase letters a-z. | ||
""" | ||
|
||
class TrieNode: | ||
def __init__(self): | ||
self.children = {} | ||
self.is_word = False | ||
|
||
class NewTrie: | ||
def __init__(self): | ||
self.root = TrieNode() | ||
|
||
def insert(self, word: str) -> None: | ||
""" | ||
Inserts a word into the trie. | ||
""" | ||
node = self.root | ||
for char in word: | ||
if char not in node.children: | ||
node.children[char] = TrieNode() | ||
node = node.children[char] | ||
node.is_word = True | ||
|
||
def search(self, word: str) -> bool: | ||
""" | ||
Returns True if the word is in the trie, False otherwise. | ||
""" | ||
node = self.root | ||
for char in word: | ||
if char not in node.children: | ||
return False | ||
node = node.children[char] | ||
return node.is_word |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import unittest | ||
from new_trie import NewTrie | ||
|
||
class TestNewTrie(unittest.TestCase): | ||
def setUp(self): | ||
self.trie = NewTrie() | ||
|
||
def test_insert_and_search(self): | ||
self.trie.insert("apple") | ||
self.assertTrue(self.trie.search("apple")) | ||
self.assertFalse(self.trie.search("app")) | ||
self.assertFalse(self.trie.search("apples")) | ||
|
||
def test_empty_string(self): | ||
self.trie.insert("") | ||
self.assertTrue(self.trie.search("")) | ||
|
||
def test_common_prefix(self): | ||
self.trie.insert("cat") | ||
self.trie.insert("car") | ||
self.assertTrue(self.trie.search("cat")) | ||
self.assertTrue(self.trie.search("car")) | ||
self.assertFalse(self.trie.search("ca")) | ||
|
||
def test_non_existent_word(self): | ||
self.trie.insert("hello") | ||
self.assertFalse(self.trie.search("world")) | ||
|
||
if __name__ == "__main__": | ||
unittest.main() |