Search code examples
pythonalgorithmbacktracking

Given a list of numbers, how do you create all the combinations of sums and return a list of those sum


Let us suppose that we have a list of numbers [1,2,3] and we have to append all the possible combinations of sum of elements in an array and return that array?

how to get the following sums

1 = 1 (the first element so simply add it to the ans array)
1 + 2 = 3
1 + 3 = 4
1 + 2 + 3 = 6
1 + 3 + 2 = 6
2 = 2 (second element so simply add it to ans array)
2 + 1 = 3
2 + 3 = 5
2 + 1 + 3 = 6
2 + 3 + 1 = 6
3 + 1 = 4
3 = 3 (third element so simply add it to ans array)
3 + 1 = 4
3 + 2 = 5
3 + 1 + 2 = 6
3 + 2 + 1 = 6

So our final array will look like [1,3,4,6,6,2,3,5,6,6,3,4,5,6,6]


Solution

  • Using itertools.permutations:

    >>> import itertools
    >>> nums = [1, 2, 3]
    >>> [sum(p) for n in range(1, len(nums)+1) for p in itertools.permutations(nums, n)]
    [1, 2, 3, 3, 4, 3, 5, 4, 5, 6, 6, 6, 6, 6, 6]
    

    If you want to see exactly what permutations is doing rather than just seeing the final sums, you can do fun things with map and join:

    >>> [f"{'+'.join(map(str, p))}={sum(p)}" for n in range(1, len(nums)+1) for p in itertools.permutations(nums, n)]
    ['1=1', '2=2', '3=3', '1+2=3', '1+3=4', '2+1=3', '2+3=5', '3+1=4', '3+2=5', '1+2+3=6', '1+3+2=6', '2+1+3=6', '2+3+1=6', '3+1+2=6', '3+2+1=6']