Advertisement
Aikiro42

trie

Jan 26th, 2020
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. class Lief:
  2.     def __init__(self, e, is_end):
  3.         self.e = e
  4.         self.children = {}
  5.         self.is_end = is_end
  6.  
  7.     def add_child(self, e):
  8.         self.children['e'] = Node(e)
  9.  
  10.     def get_child(self, e):
  11.         return self.children['e']
  12.  
  13.     def add_word(self, word):
  14.         if word[0] not in self.children:
  15.             new_lief = Lief(word[0], False)
  16.             if len(word) > 1:
  17.                 new_lief.add_word(word[1:])
  18.             else:
  19.                 new_lief.is_end = True
  20.             self.children[word[0]] = new_lief
  21.         else:
  22.             self.children[word[0]].add_word(word[1:])
  23.  
  24.     def search_word(self, word):
  25.         if word[0] == self.e:
  26.             if len(word) == 1 and self.is_end:
  27.                 return True
  28.             elif len(word) > 1 and word[0] in self.children:
  29.                 return self.children[word[0]].search_word(word[1:])
  30.             else:
  31.                
  32.         else:
  33.             return False
  34.  
  35.  
  36. class Trie:
  37.     def __init__(self):
  38.         self.heads = {}
  39.  
  40.     def add_word(self, word):
  41.         if word[0] not in self.heads:
  42.             new_lief = Lief(word[0], False)
  43.             if len(word) > 1:
  44.                 new_lief.add_word(word[1:])
  45.             else:
  46.                 new_lief.is_end = True
  47.             self.heads[word[0]] = new_lief
  48.         else:
  49.             self.heads[word[0]].add_word(word[1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement