Search code examples
pythonlistsetunionprobability

I need to solve the general equation for the union of the elements of a set to calculate propabilitys of the set in python


In math language:

list=[1,3,4]
Solve=1+3+4-1*3-1*4-3*4-1*3*4

The general function:

A1∪A2∪..∪An= A1+A2+..+An-A1*A2-A1...-A1*A2*...*An

I need to create a function to solve this problem for any number of objects in a list.

The slow way:

a=[2,2,1]

b=(a[0]|a[1]|a[2])

I need the general solution!


Solution

  • If I'm following your pattern, you can generate all the combinations of size 2..N using itertools.combinations then for each combination you can multiple the tuple using functools.reduce with the operator.mul operation. Then negate these values within sum.

    >>> from itertools import combinations
    >>> from functools import reduce
    >>> from operator import mul
    
    >>> data = [1,3,4]
    >>> sum(data) + sum(sum(-reduce(mul, i) for i in combinations(data, n)) for n in range(2, len(data)+1))
    -23