Advertisement
hoangreal

Trie pins string matching

Oct 19th, 2024
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | Source Code | 0 0
  1. class Trie:
  2.  
  3.     ### STEP 1 ###
  4.     @staticmethod
  5.     def hash(val):  # Unique and Immutable
  6.         return val
  7.  
  8.     ### STEP 2
  9.     class Node:
  10.         def __init__(self, val="", is_word_end=False):
  11.             self.val = val
  12.             self.is_word_end = is_word_end
  13.             self.children = {}
  14.  
  15.         def create_child(self, val, is_word_end=False):
  16.             key = Trie.hash(val)
  17.             if key in self.children:
  18.                 if is_word_end:
  19.                     self.children[key].is_word_end = True
  20.             else:
  21.                 # Creates a new Node instance
  22.                 self.children[key] = self.__class__(val, is_word_end)
  23.             return
  24.  
  25.         def move(self, val):
  26.             key = Trie.hash(val)
  27.             return self.children.get(key, None)
  28.  
  29.     ### STEP 3 ###
  30.     def __init__(self, inputs=[]):
  31.         self.root = self.Node()
  32.         for input_branch in inputs:
  33.             self.insert(input_branch)
  34.  
  35.     def insert(self, input_branch: str) -> None:
  36.         """Time Complexity: O(len(input_branch))"""
  37.         node = self.root
  38.         for i, val in enumerate(input_branch):
  39.            
  40.             # STEP 1: when is a node 'end of word'
  41.             if i == len(input_branch) - 1:
  42.                 node.create_child(val, True)
  43.            
  44.             elif input_branch[i + 1] == ' ':
  45.                 node.create_child(val, True)
  46.                
  47.             # STEP 2: Static
  48.             else:
  49.                 node.create_child(val, False)
  50.             node = node.move(val)
  51.         return
  52.    
  53.     def is_match(self, word: str) -> bool:
  54.         node = self.root
  55.         for char in word:
  56.             node = node.move(char)
  57.             if node is None:
  58.                 return False
  59.         return node.is_word_end == True
  60.  
  61. """
  62. Return indices of users being notified
  63. """
  64. def solve(pins_strings: list[str], user_strings: list[str]) -> list[int]:
  65.     answers = []
  66.    
  67.     trie = Trie(pins_strings)
  68.    
  69.     for i in range(len(user_strings)):
  70.         if trie.is_match(user_strings[i]):
  71.             answers.append(i)
  72.            
  73.     return answers
  74.  
  75. pins_strings = ["Trump is winning", "Nvidia is a scam", "More men more fun"]
  76. user_strings = ["Trump", "Nvidia", "Cars"]
  77. print(solve(pins_strings, user_strings))
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement