Data Structures & AlgorithmsVery hardICPC regional · subset enumeration
Problem: How many subsets of {1, 2, 3, 4} have a prime sum (the empty set has sum 0 and is not prime)? Run the code.
Problem: How many subsets of {1, 2, 3, 4} have a prime sum (the empty set has sum 0 and is not prime)? Run the code.
from itertools import combinations
a = [1, 2, 3, 4]
def prime(n):
return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1))
print(sum(1 for r in range(len(a) + 1) for c in combinations(a, r) if prime(sum(c))))What is printed?- A. 7
- B. 9
- C. 13
- D. 4
Correct answer: A. 7
The prime-sum subsets are {2}, {3}, {1,2}, {1,4}, {2,3}, {3,4} and {1,2,4}: 7. Dropping the n > 1 test makes the sums 0 and 1 'prime' (9), using range(2, int(√n)) without + 1 lets 4, 6, 8 and 9 through (13), and counting distinct prime sums 2, 3, 5, 7 gives 4.
More Coding Interview Problems questions
- Problem: How many ordered pairs (i, j) with i != j of [1, 2, 3, 4] have an even sum? Run the code. python a = [1, 2, 3, 4] print(sum(1 for…
- Problem: What does the following print? python from collections import Counter print(Counter('mississippi').mostcommon(1)) What is printed?
- Problem: What does the following print? python print(round(1.23456, 2), round(-2.5)) What is printed?
- Problem: What does the following print? python print(max([], default=-1), sum([]), divmod(-7, 3))
- Problem: What does the following print? python print(2 -1, 7 % -3)
- Problem: What does the following print? python print(sorted([3, 1, 2], key=lambda x: -x)[0]) What is printed?