Data Structures & AlgorithmsModerateTCS NQT · counting

Problem: How many 2-element subsets of {1, 2, 3, 4, 5} have an even sum? Run the code.

Problem: How many 2-element subsets of {1, 2, 3, 4, 5} have an even sum? Run the code.
from itertools import combinations
print(sum(1 for a, b in combinations([1, 2, 3, 4, 5], 2) if (a + b) % 2 == 0))
What is printed?
  1. A. 6
  2. B. 3
  3. C. 4
  4. D. 5

Correct answer: C. 4

Even sums come from two odd numbers (3 choose 2 = 3 pairs) or two even numbers (1 pair), for 4 in total.

More Coding Interview Problems questions

Exams that ask this topic