Data Structures & AlgorithmsModerateTCS NQT · subset sums

Problem: How many subsets of [1, 2, 3, 4, 5] have a sum of exactly 7? Run the code.

Problem: How many subsets of [1, 2, 3, 4, 5] have a sum of exactly 7? Run the code.
from itertools import combinations
a = [1, 2, 3, 4, 5]
print(sum(1 for r in range(len(a) + 1) for c in combinations(a, r) if sum(c) == 7))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 5
  4. D. 3

Correct answer: D. 3

The subsets are {2,5}, {3,4} and {1,2,4}. Missing the three-element subset is the common error here.

More Coding Interview Problems questions

Exams that ask this topic