trie.py


SUBMITTED BY: okpalan86

DATE: Jan. 6, 2024, 10:18 p.m.

UPDATED: March 2, 2024, 3:37 p.m.

FORMAT: Python

SIZE: 1.3 kB

HITS: 526

  1. class TrieNode:
  2. def __init__(self):
  3. self.children = {}
  4. self.is_end_of_word = False
  5. class Trie:
  6. def __init__(self):
  7. self.root = TrieNode()
  8. def insert(self, word):
  9. node = self.root
  10. for char in word:
  11. if char not in node.children:
  12. node.children[char] = TrieNode()
  13. node = node.children[char]
  14. node.is_end_of_word = True
  15. def search(self, word):
  16. node = self.root
  17. for char in word:
  18. if char not in node.children:
  19. return False
  20. node = node.children[char]
  21. return node.is_end_of_word
  22. def starts_with_prefix(self, prefix):
  23. node = self.root
  24. for char in prefix:
  25. if char not in node.children:
  26. return False
  27. node = node.children[char]
  28. return True
  29. # Example usage:
  30. trie = Trie()
  31. words = ["apple", "app", "apricot", "banana", "bat"]
  32. for word in words:
  33. trie.insert(word)
  34. print(trie.search("apple")) # True
  35. print(trie.search("app")) # True
  36. print(trie.search("apricot")) # True
  37. print(trie.search("ap")) # False
  38. # print(trie.starts_with_prefix("ban")) # True
  39. # print(trie.starts_with_prefix("bat")) # True
  40. # print(trie.starts_with_prefix("batman")) # False

comments powered by Disqus