| 8 | |
| 9 | |
| 10 | class TrieNode: |
| 11 | def __init__(self): |
| 12 | self.nodes = dict() # Mapping from char to TrieNode |
| 13 | self.is_leaf = False |
| 14 | |
| 15 | def insert_many(self, words: [str]): # noqa: E999 This syntax is Python 3 only |
| 16 | """ |
| 17 | Inserts a list of words into the Trie |
| 18 | :param words: list of string words |
| 19 | :return: None |
| 20 | """ |
| 21 | for word in words: |
| 22 | self.insert(word) |
| 23 | |
| 24 | def insert(self, word: str): # noqa: E999 This syntax is Python 3 only |
| 25 | """ |
| 26 | Inserts a word into the Trie |
| 27 | :param word: word to be inserted |
| 28 | :return: None |
| 29 | """ |
| 30 | curr = self |
| 31 | for char in word: |
| 32 | if char not in curr.nodes: |
| 33 | curr.nodes[char] = TrieNode() |
| 34 | curr = curr.nodes[char] |
| 35 | curr.is_leaf = True |
| 36 | |
| 37 | def find(self, word: str) -> bool: # noqa: E999 This syntax is Python 3 only |
| 38 | """ |
| 39 | Tries to find word in a Trie |
| 40 | :param word: word to look for |
| 41 | :return: Returns True if word is found, False otherwise |
| 42 | """ |
| 43 | curr = self |
| 44 | for char in word: |
| 45 | if char not in curr.nodes: |
| 46 | return False |
| 47 | curr = curr.nodes[char] |
| 48 | return curr.is_leaf |
| 49 | |
| 50 | |
| 51 | def print_words(node: TrieNode, word: str): # noqa: E999 This syntax is Python 3 only |