ProgrammingModerateInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
from collections import defaultdict
words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
g = defaultdict(list)
for w in words:
    g[''.join(sorted(w))].append(w)
print(list(g.values()))
  1. A. [['eat', 'tea', 'ate'], ['bat'], ['tan', 'nat']]
  2. B. [['ate', 'eat', 'tea'], ['tan', 'nat'], ['bat']]
  3. C. [['tan', 'nat'], ['eat', 'tea', 'ate'], ['bat']]
  4. D. [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Correct answer: D. [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

defaultdict keeps keys in first-seen order, and the sorted letters act as keys. eat, tea and ate share the key aet, then tan and nat share ant, and bat stands alone.

More Python Programming questions

Exams that ask this topic