Is there a name for this operation? And: is there a closed-form expression?
- For a given set of n elements, and value k between 1 and n,
- Take all subsets (combinations) of k items
- Find the product of each subset
- Find the sum of all those products
I can express this in Python, and do the calculation pretty easily:
from operator import mul
from itertools import combinations
from functools import reduce
def sum_of_product_of_subsets(list1, k):
val = 0
for subset in combinations(list1, k):
val += reduce(mul, subset)
return val
I’m just looking for the closed form expression, so as to avoid the loop in case the set size gets big.
Note this is NOT the same as this question: Sum of the product over all combinations with one element from each group — that question is about the sum-of-products of a Cartesian product. I’m looking for the sum-of-products of the set of combinations of size k; I don’t think they are the same.
To be clear, for set(a, b, c, d), then:
k = 4 --> a*b*c*d
k = 3 --> b*c*d + a*c*d + a*b*d + a*b*c
k = 2 --> a*b + a*c + a*d + b*c + b*d + c*d
k = 1 --> a + b + c + d
Just looking for the expression; no need to supply the Python code specifically. (Any language would be illustrative, if you’d like to supply an example implementation.)
These are elementary symmetric polynomials. You can write them using summation signs as in Wikipedia. You can also use Vieta’s formulas to get all of them at once as coefficients of a polynomial (up to signs)
By expanding (x-a_1)(x-a_2)…(x-a_k) you get a polynomial time algorithm to compute all those numbers (your original implementation runs in exponential time).
Edit: Python implementation:
That gives you [24, 26, 9, 1], as 2*3*4=24, 2*3+2*4+3*4=26, 2+3+4=9. That last 1 is the empty product, which corresponds to k=0 in your implementation.
This should be O(N2). Using polynomial FFT you could do O(N log2 N), but I am too lazy to code that.