ProgrammingHardCognizant GenC · TCS NQT

What is printed?

What is printed?
words = 'the cat and the dog and the end'.split()
cnt = {}
for w in words:
    cnt[w] = cnt.get(w, 0) + 1
top = sorted(cnt, key=lambda w: -cnt[w])[:3]
print(top)
  1. A. ['the', 'and', 'end']
  2. B. ['the', 'and', 'dog']
  3. C. ['the', 'cat', 'and']
  4. D. ['the', 'and', 'cat']

Correct answer: D. ['the', 'and', 'cat']

Sorting by negative count is stable, so among words with one occurrence the earliest inserted word, cat, comes first. Dict insertion order decides ties.

More Python Programming questions

Exams that ask this topic