Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1.  
  2. class TrieNode(object):
  3.  
  4. def __init__(self):
  5. self.nodes = [None] * 26 # 1 for each letter in alphabet
  6. self.terminating = False # Flag to determine termination
  7.  
  8. def insert(self, word):
  9. word = word.lower()
  10. index = ord(word[0]) - 97 # Remove 97 to make it a-z = 0-25
  11.  
  12. # If the indexue of the child node at the index is None, make a new trie
  13. # there to represent the letter
  14. if self.nodes[index] is None:
  15. self.nodes[index] = TrieNode()
  16.  
  17. # if the word length is greater 1, then we are still adding the word.
  18. # otherwise, set the terminating flag to True so we know a word ends here.
  19. if len(word) > 1:
  20. self.nodes[index].insert(word[1:])
  21. else:
  22. self.nodes[index].terminating = True
  23.  
  24. def has(self, word):
  25. word = word.lower()
  26. word_len = len(word)
  27. index = ord(word[0]) - 97
  28.  
  29. if self.nodes[index] is not None and word_len > 1:
  30. return self.nodes[index].has(word[1:])
  31. elif self.nodes[index].terminating is True and word_len == 1:
  32. return True
  33.  
  34. return False
  35.  
  36. @classmethod
  37. def from_file(cls, fname):
  38. node = cls()
  39. with open(fname, 'r') as fh:
  40. for line in fh.readlines():
  41. pass
  42. return node
  43.  
  44. def to_file(self, fname):
  45. def inner(node, path):
  46. for index, node in enumerate(node.nodes):
  47. if node is not None:
  48. path += [index]
  49. if node.terminating:
  50. yield path, node.terminating
  51. for item in inner(node, path):
  52. yield item
  53. path.pop()
  54.  
  55. with open(fname, 'w') as fh:
  56. for path, terminating in inner(self, []):
  57. print(f"{path!r}{int(terminating)}\n")
  58.  
  59. testing_words = ["testings","test","testing","tesla","teslas","master","masters","bar"]
  60. t = TrieNode()
  61. for word in testing_words:
  62. t.insert(word)
  63. for word in testing_words:
  64. assert t.has(word)
  65.  
  66. t.to_file("testing.out")
  67. # TrieNode.from_file("testing.out")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement