ProgrammingVery hardProduct company OA

What is printed?

What is printed?
from itertools import groupby
s = "aabbbaac"
g1 = [(k, len(list(v))) for k, v in groupby(s)]
g2 = {k: len(list(v)) for k, v in groupby(s)}
print(len(g1), g2, [k for k, v in groupby(sorted(s))], max(g1, key=lambda p: p[1]))
  1. A. 3 {'a': 4, 'b': 3, 'c': 1} ['a', 'b', 'c'] ('a', 4)
  2. B. 4 {'a': 4, 'b': 3, 'c': 1} ['a', 'b', 'c'] ('b', 3)
  3. C. 4 {'a': 2, 'b': 3, 'c': 1} ['a', 'b', 'c'] ('b', 3)
  4. D. 4 {'a': 2, 'b': 3, 'c': 1} ['a', 'b', 'a', 'c'] ('b', 3)

Correct answer: C. 4 {'a': 2, 'b': 3, 'c': 1} ['a', 'b', 'c'] ('b', 3)

groupby only merges CONSECUTIVE equal items (it is a run-length grouper, not SQL GROUP BY). The runs are aa, bbb, aa, c → 4 groups. In the dict comprehension the second run of 'a' overwrites the first, so 'a' maps to 2, not 4. Sorting first makes equal letters adjacent → keys a, b, c. The longest run is ('b', 3). The option with 3 groups and 'a': 4 is what you get only after sorting the input.

More Python Programming questions

Exams that ask this topic