ProgrammingModerateTCS NQT · Infosys

What is printed?

What is printed?
words = 'the quick brown the lazy the'.split()
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:3])
  1. A. [('the', 3), ('quick', 1), ('brown', 1)]
  2. B. [('the', 3), ('brown', 1), ('lazy', 1)]
  3. C. [('the', 3), ('lazy', 1), ('brown', 1)]
  4. D. [('the', 3), ('brown', 1), ('quick', 1)]

Correct answer: B. [('the', 3), ('brown', 1), ('lazy', 1)]

The key sorts by descending count and then alphabetically, so among the words with count 1 the alphabetical order gives brown and then lazy. The key (-count, word) is the standard way to sort by two criteria with different directions.

More Python Programming questions

Exams that ask this topic