ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from itertools import groupby
s = 'aabbaa'
print([(k, len(list(g))) for k, g in groupby(s)])
  1. A. [('a', 4), ('b', 2)]
  2. B. [('a', 2), ('b', 2)]
  3. C. [('b', 2), ('a', 4)]
  4. D. [('a', 2), ('b', 2), ('a', 2)]

Correct answer: D. [('a', 2), ('b', 2), ('a', 2)]

groupby merges only consecutive equal keys, so the two runs of a are reported separately. People who expect a dict or Counter result often get this wrong.

More Python Programming questions

Exams that ask this topic