Predict the output
What does this print?
items = [1, 2, 3]
out = []
for mask in range(1 << len(items)):
pick = [x for i, x in enumerate(items) if mask >> i & 1]
if len(pick) == 2:
out.append(pick)
print(out)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [[1, 2], [1, 3], [2, 3]]
Right: masks 3, 5 and 6 have two bits set.
Each of the 2ⁿ masks is one selection, which is why the full listing costs O(n · 2ⁿ) however it is generated.
Why not the others?
- B [[1, 2], [2, 3]]. Mask 5 picks 1 and 3.
- C [[2, 1], [3, 1], [3, 2]]. Items are taken in list order.