ProgrammingHardPython · GATE DA · Advanced

What is printed?

What is printed?
import itertools
data = [1, 1, 2, 1, 1, 1, 3]
print([(k, len(list(g))) for k, g in itertools.groupby(data)])
print(sorted(itertools.groupby(data), key=lambda t: t[0])[0][0])
  1. A. [(1, 5), (2, 1), (3, 1)] / 3
  2. B. [(1, 2), (2, 1), (1, 3), (3, 1)] / 3
  3. C. [(1, 5), (2, 1), (3, 1)] / 1
  4. D. [(1, 2), (2, 1), (1, 3), (3, 1)] / 1

Correct answer: D. [(1, 2), (2, 1), (1, 3), (3, 1)] / 1

groupby only groups consecutive equal keys, so 1 appears as two separate runs (lengths 2 and 3); the second line only reads keys, so the smallest key is 1.

More Python Programming questions

Exams that ask this topic