Iam_Sandeep

Trie Implementation in Python using dictionary

Jun 15th, 2022 (edited)
757
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. '''
  2. Method 1:
  3. '''
  4. class Trie:
  5.  
  6.     def __init__(self):
  7.         self.root={}
  8.        
  9.  
  10.     def insert(self, word: str) -> None:
  11.         cur=self.root
  12.         for char in word:
  13.             cur=cur.setdefault(char,{})
  14.  
  15.         cur['*']=True
  16.  
  17.     def search(self, word: str) -> bool:
  18.         cur=self.root
  19.         for char in word:
  20.             if char not in cur:
  21.                 return False
  22.             else:
  23.                 cur=cur[char]
  24.        
  25.         if '*' in cur:
  26.             return True
  27.         else:
  28.             return False
  29.        
  30.  
  31.     def startsWith(self, pref: str) -> bool:
  32.         cur=self.root
  33.         for char in pref:
  34.             if char not in cur:
  35.                 return False
  36.             cur=cur[char]
  37.         return True
  38. '''
  39. Method 2:
  40. '''
  41.  
  42. class Trie:
  43.  
  44.     def __init__(self):
  45.         self.root={}
  46.        
  47.  
  48.     def insert(self, word: str) -> None:
  49.         cur=self.root
  50.         for char in word:
  51.             if char in cur:
  52.                 cur=cur[char]
  53.             else:
  54.                 cur[char]={}
  55.                 cur=cur[char]
  56.         cur['*']=True
  57.  
  58.     def search(self, word: str) -> bool:
  59.         cur=self.root
  60.         for char in word:
  61.             if char not in cur:
  62.                 return False
  63.             else:
  64.                 cur=cur[char]
  65.        
  66.         if '*' in cur:
  67.             return True
  68.         else:
  69.             return False
  70.        
  71.  
  72.     def startsWith(self, pref: str) -> bool:
  73.         cur=self.root
  74.         for char in pref:
  75.             if char not in cur:
  76.                 return False
  77.             cur=cur[char]
  78.         return True
  79.  
Add Comment
Please, Sign In to add comment