Predict the output
What does this print?
bits = [0] * 9
for i in range(1, len(bits)):
bits[i] = bits[i >> 1] + (i & 1)
print(bits)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [0, 1, 1, 2, 1, 2, 2, 3, 1]
Right: for example 7 is 111 (three bits) and 8 is 1000 (one bit).
Each entry costs one shift and one addition, because the count for i >> 1 is always computed first.
Why not the others?
- B [0, 1, 2, 2, 3, 3, 3, 3, 4]. Those are bit lengths, not counts of 1 bits.
- C [0, 1, 1, 2, 1, 2, 2, 3, 2]. 8 is a power of two, so it has a single 1 bit.