Skip to content

Commit

Permalink
Add new trie algorithm with insert and search functions
Browse files Browse the repository at this point in the history
  • Loading branch information
staging-devin-ai-integration[bot] committed Aug 23, 2024
1 parent 1ee7c81 commit 276bb2b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
37 changes: 37 additions & 0 deletions tree/trie/new_trie.py
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
30 changes: 30 additions & 0 deletions tree/trie/test_new_trie.py
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()

0 comments on commit 276bb2b

Please sign in to comment.