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'))- A. 3 0
- B. 4 1
- C. 2 0
- 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
- What is printed? python M = 109 + 7 N = 10 fact = [1] (N + 1) for i in range(1, N + 1): fact[i] = fact[i - 1] i % M def nCr(n, r): return…
- What is printed? python def summin(a): MOD = 109 + 7 st = [] total = 0 cur = 0 for x in a: cnt = 1 while st and st[-1][0] >= x: v, c =…
- What is printed? python print(6 & 3 == 2, 5 | 2 == 7)
- What is printed? python import heapq def medians(xs): lo, hi = [], [] out = [] for x in xs: heapq.heappush(lo, -x) heapq.heappush(hi…
- What is printed? python def sieve(n): s = bytearray([1]) (n + 1) s[0:2] = bytes(2) for i in range(2, int(n 0.5) + 1): if s[i]: s[i i::i] =…
- What is printed? python a = [1, 2, 3] b = a b += [4] c = a + [5] a = a 2 print(b, c, a)