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]))- A. [1, 2, 4, 5, 7, 8, 10, 11] [1, 3, 5, 7, 9, 11]
- B. [1, 5, 7, 11] [1, 5, 7, 11]
- C. [1, 3, 5, 7, 9, 11] [1, 2, 4, 5, 7, 8, 10, 11]
- 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
- What is printed? python class V: def init(self, n, log): self.n, self.log = n, log def add(self, o): self.log.append("add"); return…
- What is printed? python log = [] def t(x): log.append(x); return x def f(a, b=t("d1"), args, c=t("d2"), kw): return a, b, args, c…
- What is printed? python d = dict.fromkeys("ab", []) d["a"].append(1) d["b"] = d["b"] + [2] d["a"] += [3] g = [[]] 2 + [[] for in range(2)]…
- A log pipeline must remove duplicate event ids from a list xs of n = 2·10⁵ integers while keeping the order of first occurrence. Four…
- What is printed? python class Base: registry = [] def initsubclass(cls, kw): cls.registry.append(cls.name) cls.tag = kw.get("tag"…
- What is printed? python class CM: def init(self, name, swallow): self.name, self.swallow = name, swallow def enter(self): print("in" +…