ProgrammingVery hardProduct company OA

What is printed?

What is printed?
calls = []
def chk(x):
    calls.append(x)
    return x > 2

r1 = any(chk(x) for x in [1, 3, 5])
r2 = all([chk(x) for x in [4, 0, 6]])
r3 = any(map(chk, [0, 7, 9]))
print(r1, r2, r3, calls)
  1. A. True False True [1, 3, 5, 4, 0, 6, 0, 7, 9]
  2. B. True False True [1, 3, 4, 0, 0, 7]
  3. C. True False True [1, 3, 4, 0, 6, 0, 7]
  4. D. True True True [1, 3, 4, 0, 6, 0, 7]

Correct answer: C. True False True [1, 3, 4, 0, 6, 0, 7]

any and all short-circuit, but only lazy inputs benefit. The generator stops after chk(3) returns True (5 is never checked). The LIST comprehension calls chk on 4, 0 and 6 before all() even starts, then all returns False. map is lazy, so any stops after 7. Calls: 1, 3, 4, 0, 6, 0, 7.

More Python Programming questions

Exams that ask this topic