ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
def gen(n):
    if n == 0:
        yield ""
        return
    for s in gen(n - 1):
        yield s + "0"
        if not s.endswith("1"):
            yield s + "1"
print(list(gen(3)))
  1. A. ['000', '001', '010', '011', '100', '101', '110', '111']
  2. B. ['000', '001', '010', '100', '101', '110']
  3. C. ['000', '001', '010', '100', '101']
  4. D. ['000', '010', '100', '101']

Correct answer: C. ['000', '001', '010', '100', '101']

A '1' is appended only when the string does not already end in '1', so no two 1s are adjacent. This recursive generator yields the 5 such strings of length 3 in that order.

More Python Programming questions

Exams that ask this topic