Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: What is the number of distinct subsets sums obtainable from {2, 3, 7} (including the empty subset)? Run the code.

Problem: What is the number of distinct subsets sums obtainable from {2, 3, 7} (including the empty subset)? Run the code.
from itertools import combinations
a = [2, 3, 7]
print(len({sum(c) for r in range(len(a) + 1) for c in combinations(a, r)}))
What is printed?
  1. A. 7
  2. B. 8
  3. C. 13
  4. D. 6

Correct answer: B. 8

Sums 0, 2, 3, 5, 7, 9, 10, 12 are all different, so 8. Leaving out the empty sum gives 7, assuming every value 0..12 is reachable gives 13, and 6 counts only 1- and 2-element subsets.

More Coding Interview Problems questions

Exams that ask this topic