Shrihari
Shrihari

Reputation: 123

Possible Sum Of Numbers in a List

List1=[1,2,3]

I want an output like below

[6,5,4,3]

That is the maximum sum is 6. But what I like to do is I want all possible sums inside that list. That is 3+2 , 2+1 , 1+3 , etc.. like all possible ways.

Upvotes: 0

Views: 93

Answers (1)

Brad Solomon
Brad Solomon

Reputation: 40918

How's this work for you?

from itertools import chain, combinations

list1 = [1, 2, 3]    
n = len(list1)
c = (combinations(list1, r) for r in range(2, n+1))
c = set(sum(i) for i in chain.from_iterable(c))

print(c)
# {3, 4, 5, 6}

The result will be unique sums of each combination of length r, with r running from 2 up thru the length of your input list. The result uses a set constructor to guarantee unique values.

In a function:

def unique_sum(obj):
    return set(sum(i) for i in chain.from_iterable(
        combinations(obj, r) for r in range(2, len(obj)+1)))

unique_sum([5, 5, 5])
# {10, 15}

Upvotes: 1

Related Questions