Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TrieNode(object):
- def __init__(self):
- self.nodes = [None] * 26 # 1 for each letter in alphabet
- self.terminating = False # Flag to determine termination
- def insert(self, word):
- word = word.lower()
- index = ord(word[0]) - 97 # Remove 97 to make it a-z = 0-25
- # If the indexue of the child node at the index is None, make a new trie
- # there to represent the letter
- if self.nodes[index] is None:
- self.nodes[index] = TrieNode()
- # if the word length is greater 1, then we are still adding the word.
- # otherwise, set the terminating flag to True so we know a word ends here.
- if len(word) > 1:
- self.nodes[index].insert(word[1:])
- else:
- self.nodes[index].terminating = True
- def has(self, word):
- word = word.lower()
- word_len = len(word)
- index = ord(word[0]) - 97
- if self.nodes[index] is not None and word_len > 1:
- return self.nodes[index].has(word[1:])
- elif self.nodes[index].terminating is True and word_len == 1:
- return True
- return False
- @classmethod
- def from_file(cls, fname):
- node = cls()
- with open(fname, 'r') as fh:
- for line in fh.readlines():
- pass
- return node
- def to_file(self, fname):
- def inner(node, path):
- for index, node in enumerate(node.nodes):
- if node is not None:
- path += [index]
- if node.terminating:
- yield path, node.terminating
- for item in inner(node, path):
- yield item
- path.pop()
- with open(fname, 'w') as fh:
- for path, terminating in inner(self, []):
- print(f"{path!r}{int(terminating)}\n")
- testing_words = ["testings","test","testing","tesla","teslas","master","masters","bar"]
- t = TrieNode()
- for word in testing_words:
- t.insert(word)
- for word in testing_words:
- assert t.has(word)
- t.to_file("testing.out")
- # TrieNode.from_file("testing.out")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement