ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
words = ['tea', 'eat', 'tan', 'ate', 'nat']
groups = {}
for w in words:
    groups.setdefault(''.join(sorted(w)), []).append(w)
print(len(groups), groups['aet'])
  1. A. 2 ['tea', 'eat', 'ate']
  2. B. 3 ['tea', 'eat', 'ate']
  3. C. 2 ['tea', 'eat']
  4. D. 2 ['eat', 'tea', 'ate']

Correct answer: A. 2 ['tea', 'eat', 'ate']

Anagrams share the same sorted key. tea, eat and ate share the key aet, and tan and nat share ant, so there are 2 groups. The aet group keeps the input order.

More Python Programming questions

Exams that ask this topic