Predict the output
What does this print?
from itertools import combinations
vals, k = [1, 5, 3, 3, 7], 2
pairs = combinations(vals, 2) # every pair of positions
slow = sum(1 for a, b in pairs if abs(a - b) == k)
print(slow)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 5
Right: 1 pairs with both 3s, 5 pairs with both 3s, and 5 pairs with 7.
This O(n²) count is the baseline that the next page speeds up to O(n) with a counter of earlier values.
Why not the others?
- B 3. Each copy of 3 forms its own pair with 1 and with 5.
- C 4. 5 and 7 also differ by 2.