ProgrammingVery hardProduct company OA

What is printed?

What is printed?
def chain(nums, divisors):
    g = (n for n in nums)
    for d in divisors:
        g = (n for n in g if n % d)
    return list(g)
print(chain(range(1, 13), [2, 3]), chain(range(1, 13), [3, 2]))
  1. A. [1, 2, 4, 5, 7, 8, 10, 11] [1, 3, 5, 7, 9, 11]
  2. B. [1, 5, 7, 11] [1, 5, 7, 11]
  3. C. [1, 3, 5, 7, 9, 11] [1, 2, 4, 5, 7, 8, 10, 11]
  4. D. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Correct answer: A. [1, 2, 4, 5, 7, 8, 10, 11] [1, 3, 5, 7, 9, 11]

In a generator expression only the first iterable (g) is bound when the expression is created; the name d inside the condition is looked up when the generator actually runs, i.e. inside list(g) after the loop has finished. Both stacked filters therefore test the LAST divisor: for [2, 3] you get the numbers not divisible by 3, for [3, 2] the odd numbers. The intended sieve result [1, 5, 7, 11] needs d frozen, e.g. via a helper function or default argument.

More Python Programming questions

Exams that ask this topic