Embercode
✕
TriesQuick quiz

Roots and longest word

8 questions. Covers Longest word built one letter at a time.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``python class Node: def __init__(self): self.children = [None] * 26 self.is_end = False def insert(root, word): node = root for ch in word: i = ord(ch) - ord("a") if node.children[i] is None: node.children[i] = Node() node = node.children[i] node.is_end = True def shortest_root(root, word): node = root for i, ch in enumerate(word): node = node.children[ord(ch) - ord("a")] if node is None: return word if node.is_end: return word[: i + 1] return word def replace_words(roots, sentence): root = Node() for r in roots: insert(root, r) words = sentence.split(" ") return " ".join(shortest_root(root, w) for w in words) print(replace_words(["tr", "try", "ee"], "tryout dog eel") + " | " + replace_words(["batt", "bat", "ba"], "batter")) ``
  2. 2. What does this program print? ``python class TrieNode: def __init__(self): self.children = {} self.is_word = False class LongestWord: def __init__(self): self.root = TrieNode() self.best = "" def insert(self, word): node = self.root for ch in word: if ch not in node.children: node.children[ch] = TrieNode() node = node.children[ch] node.is_word = True def longest_buildable(self): self.best = "" self._explore(self.root, []) return self.best def _explore(self, node, path): for ch, child in node.children.items(): if not child.is_word: continue path.append(ch) word = "".join(path) if len(word) > len(self.best) or (len(word) == len(self.best) and word < self.best): self.best = word self._explore(child, path) path.pop() def solve(words): trie = LongestWord() for w in words: trie.insert(w) return trie.longest_buildable() print(solve(["o", "on", "one", "ones", "once", "onex"])) ``
  3. 3. The roots are batt, bat and ba. What does shortest_root return for the word batter?
  4. 4. In _explore in lesson 08, why is a child skipped when its is_word flag is False?
  5. 5. Which str method, used in replace_words, cuts the sentence into words at each space?

    Type your answer.

5 question(s) left on this page.

Typed answers ignore extra spaces and, for most questions, capital letters.