Search code examples
pythonsum

sum of elements in list, when an element can take two different values


I have a list of elements and want to get the sum of this list: a = [4, 5, "X", "X"]. But X can be 2 different values, 2 or 3. So there are 4 sums of this list:

sum1 = sum([4, 5, 2, 2]) = 13
sum2 = sum([4, 5, 2, 3]) = 14
sum3 = sum([4, 5, 3, 2]) = 14
sum4 = sum([4, 5, 3, 3]) = 15

Basically I want to get a tuple (or list) of all possible sums of the list, like:

sums = (13, 14, 14, 15)

For an input list with 0 X, I want to get a tuple with 1 element, for a tuple with 1 X a tuple of 2 elements, with 2 X tuple with 4 elements...with n X a tuple of 2^n elements.


Solution

  • You can use itertools.product and a list comprehension

    from itertools import product
    
    a = [4, 5, "X", "X"]
    r = a.count('X')
    [sum(a[:len(a)-r] + [*i]) for i in product([2,3], repeat=r)]
    

    Output

    [13, 14, 14, 15]
    

    Testing with more cases

    #test cases
    for n in range(5):
        a=[4,5, *['X']*n]  # [4,5] .... [4,5,'X','X','X','X']
        r = a.count('X')
        print([sum(a[:len(a)-r] + [*i]) for i in product([2,3], repeat=r)])
    

    Output

    [9]
    [11, 12]
    [13, 14, 14, 15]
    [15, 16, 16, 17, 16, 17, 17, 18]
    [17, 18, 18, 19, 18, 19, 19, 20, 18, 19, 19, 20, 19, 20, 20, 21]