ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def chunks(xs, k):
    for i in range(0, len(xs), k):
        yield xs[i:i + k]
def flatten(seq):
    for s in seq:
        if isinstance(s, list):
            yield from flatten(s)
        else:
            yield s
print(list(chunks("abcdefg", 3)), list(flatten([1, [2, [3, []], "45"]])))
  1. A. ['abc', 'def', 'g'] [1, 2, 3, '45']
  2. B. ['abc', 'def'] [1, 2, 3, '45']
  3. C. ['abc', 'def', 'g'] [1, 2, 3, '4', '5']
  4. D. [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] [1, 2, 3, '45']

Correct answer: A. ['abc', 'def', 'g'] [1, 2, 3, '45']

Slicing a string yields strings, and the last chunk is shorter. flatten recurses only into lists, so the empty list contributes nothing and the string '45' is yielded whole.

More Python Programming questions

Exams that ask this topic