trie.py


SUBMITTED BY: okpalan86

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

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

FORMAT: Text only

SIZE: 2.2 kB

HITS: 526

  1. class TrieNode:
  2. def __init__(self):
  3. self.children = {} # Initialize children as an empty dictionary
  4. self.is_end_of_word = False # Initialize is_end_of_word as False
  5. class Trie:
  6. def __init__(self):
  7. self.root = TrieNode() # Initialize root as a TrieNode
  8. def insert(self, word):
  9. """Insert a word into the Trie."""
  10. node = self.root
  11. for char in word:
  12. if char not in node.children:
  13. node.children[char] = TrieNode()
  14. node = node.children[char]
  15. node.is_end_of_word = True
  16. def search(self, word):
  17. """Search for a word in the Trie. Return True if found, False otherwise."""
  18. node = self.root
  19. for char in word:
  20. if char not in node.children:
  21. return False
  22. node = node.children[char]
  23. return node.is_end_of_word
  24. def starts_with_prefix(self, prefix):
  25. """Check if any word in the Trie starts with the given prefix."""
  26. node = self.root
  27. for char in prefix:
  28. if char not in node.children:
  29. return False
  30. node = node.children[char]
  31. return True
  32. def ends_with_suffix(self, suffix):
  33. """Check if any word in the Trie ends with the given suffix."""
  34. node = self.root
  35. for char in suffix:
  36. if char not in node.children:
  37. return False
  38. node = node.children[char]
  39. return node.is_end_of_word
  40. def delete(self, word):
  41. """Delete a word from the Trie."""
  42. def _delete(node, word, index):
  43. if index == len(word):
  44. if not node.is_end_of_word:
  45. return False
  46. node.is_end_of_word = False
  47. return len(node.children) == 0
  48. char = word[index]
  49. if char not in node.children:
  50. return False
  51. should_delete_node = _delete(node.children[char], word, index + 1)
  52. if should_delete_node:
  53. del node.children[char]
  54. return len(node.children) == 0
  55. return False
  56. _delete(self.root, word, 0)

comments powered by Disqus