ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
print([sum(i for i in range(3) if m >> i & 1) for m in range(8)])
  1. A. [0, 1, 1, 2, 2, 3, 3, 4]
  2. B. [0, 0, 1, 1, 2, 2, 3, 4]
  3. C. [0, 0, 1, 1, 2, 2, 3, 3]
  4. D. [0, 1, 2, 3, 4, 5, 6, 7]

Correct answer: C. [0, 0, 1, 1, 2, 2, 3, 3]

In Python >> binds tighter than &, so m >> i & 1 tests bit i of m. Each mask selects a subset of the indices {0, 1, 2}, and the sum is taken over the indices in that subset.

More Python Programming questions

Exams that ask this topic