Sums generated with given integers

Question:

I’m trying to make a program that calculates the different sums that can be generated with the given integers. I’m not quite getting the hang of things, and I don’t really understand where and what to edit in the code.
I’m trying to follow the following rule (examples)
list [1,2,3] has 6 possible sums: 1, 2, 3, 4, 5 and 6
list [2,2,3] has 5 possible sums: 2, 3, 4, 5 and 7

list2 = [2, 2, 3] 

def sums(list2):
    if len(list2) == 1:
        return [list2[0]]
    else:
        new_list = []
        for x in sums(list2[1:]):
            new_list.append(x)
            new_list.append(x + list2[0])
        return new_list

print(sums(list2))

In the current code I’m struggling on getting the single integers (2, 3) and removing the duplicates. Help would be appreciated.

Asked By: Daniel

||

Answers:

I am using permutations module from itertools.

#[list(p(list1,x)) for x in range(1,len(list1)+1)]

#[[(2,), (2,), (3,)],
#[(2, 2), (2, 3), (2, 2), (2, 3), (3, 2), (3, 2)],
#[(2, 2, 3), (2, 3, 2), (2, 2, 3), (2, 3, 2), (3, 2, 2), (3, 2, 2)]]

In the above code you get all the single values, double values and triple values.

Finally I am doing a summation of these values and adding them to set to remove duplicates.

s=set()
from itertools import permutations as p
list1 = [1, 2, 3] 
for x in range(1,len(list1)+1):
    {s.add(sum(x)) for x in p(list1,x)}

print(s)
{1, 2, 3, 4, 5, 6}

#list1 = [2, 2, 3]
{2, 3, 4, 5, 7}
Answered By: Talha Tayyab

There are mainly two things you might want to modify: (i) add the case where you append list2[0] itself, and (ii) use set to take unique numbers:

def sums(list2):
    if len(list2) == 1:
        return {list2[0]}
    else:
        new_list = [list2[0]] # NOTE THAT THIS LINE HAS BEEN CHANGED
        for x in sums(list2[1:]):
            new_list.append(x)
            new_list.append(x + list2[0])
        return set(new_list)

print(sums([1,2,3])) # {1, 2, 3, 4, 5, 6}
print(sums([2,2,3])) # {2, 3, 4, 5, 7}

Alternatively, using union operator |:

def sums(lst):
    if not lst:
        return set()
    sums_recurse = sums(lst[1:])
    return {lst[0]} | sums_recurse | {lst[0] + x for x in sums_recurse}
Answered By: j1-lee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.