fahadkalil

trie.py

Oct 7th, 2025
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | Source Code | 0 0
  1. #
  2. # Original code by:
  3. # https://wangyy395.medium.com/implement-a-trie-in-python-e8dd5c5fde3a
  4. #
  5.  
  6. from collections import defaultdict
  7.  
  8. class TrieNode:
  9.     def __init__(self):
  10.         self.children = defaultdict(TrieNode)
  11.         self.is_end = False
  12.        
  13. class Trie:
  14.     def __init__(self):
  15.         """
  16.        Initialize your data structure here.
  17.        """
  18.         self.root = TrieNode()
  19.        
  20.     def insert(self, word: str) -> None:
  21.         """
  22.        Inserts a word into the trie.
  23.        """
  24.         current = self.root
  25.         for letter in word:
  26.             current = current.children[letter]
  27.         current.is_end = True
  28.        
  29.     def search(self, word: str) -> bool:
  30.         """
  31.        Returns if the word is in the trie.
  32.        """
  33.         current = self.root
  34.         for letter in word:
  35.             current = current.children.get(letter)
  36.             if current is None:
  37.                 return False
  38.         return current.is_end
  39.    
  40.     def starts_with(self, prefix: str) -> bool:
  41.         """
  42.        Returns if there is any word in the trie that starts with the given prefix.
  43.        """
  44.         current = self.root
  45.        
  46.         for letter in prefix:
  47.             current = current.children.get(letter)
  48.             if not current:
  49.                 return False
  50.        
  51.         return True
  52.  
  53. if __name__ == '__main__':
  54.     t = Trie()
  55.     t.insert('águia')
  56.     t.insert('água')
  57.  
  58.     palavra = 'água'
  59.     print(f"A palavra {palavra} existe na Trie? {t.search(palavra)}" )
  60.    
  61.     prefixo = 'águ'
  62.     print(f"Existem palavras que possuem o prefixo '{prefixo}'? {t.starts_with(prefixo)}")
  63.  
Advertisement
Add Comment
Please, Sign In to add comment