ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
a = [1, 2, 4]
cnt = 0
for mask in range(1 << len(a)):
    s = sum(a[i] for i in range(len(a)) if mask >> i & 1)
    if s % 3 == 0:
        cnt += 1
print(cnt)
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 1

Correct answer: B. 3

The loop tries all 8 bitmasks and tests each subset sum modulo 3. The empty set, {1,2} and {2,4} qualify, so the count is 3.

More Python Programming questions

Exams that ask this topic