Search code examples
pythonsum

Sums generated with given integers


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.


Solution

  • 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}