ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def trie_count(words, pref):
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node['#'] = node.get('#', 0) + 1
    node = root
    for ch in pref:
        if ch not in node:
            return 0
        node = node[ch]
    def cnt(n):
        return sum(cnt(v) if isinstance(v, dict) else v for v in n.values())
    return cnt(node)
print(trie_count(['app', 'apple', 'ape', 'bat', 'app'], 'ap'), trie_count(['app'], 'x'))
  1. A. 3 0
  2. B. 4 1
  3. C. 2 0
  4. D. 4 0

Correct answer: D. 4 0

Each word ends with a counter stored under '#'. The subtree under the prefix ap holds app twice, apple once and ape once, which totals 4. A prefix missing from the trie counts as 0.

More Python Programming questions

Exams that ask this topic