Search code examples
pythonlistfor-loopwhile-looppython-itertools

How to print all possible combinations of a list that have the same sum as the original list?


I am trying to print all possible combinations of a list but only if the combinations add up to a number.

lst = [0, 1, 2] #The goal is print all combinations that sum up to 3

import itertools

def fun(lst, total):
    sum = 0
    for element in lst:
        sum += element
        all_possible_combinations = set(itertools.product(lst, repeat=2)) # This prints all possible combinations of the elements in the list with length of 2
        for items in all_possible_combinations:
            a = 0
            for i in items:
                a += i
            if a == total:
                x = items
                print(x)
    print('These are all combinations:', all_possible_combinations)

fun([0, 1, 2], 2)

This programme prints the lists with a sum of 3 but it prints these lists more than once.

>>>>>>>>
(2, 0)
(1, 1)
(0, 2)  #I was expecting the programme to stop here.
(2, 0)
(1, 1)
(0, 2)
(2, 0)
(1, 1)
(0, 2)
These are all combinations: {(0, 1), (1, 2), (0, 0), (2, 1), (2, 0), (1, 1), (2, 2), (1, 0), (0, 2)}
>>>>>>>>

I thought that this was because of the for element in lst: loop so I tried to print outside this loop

import itertools

def fun(lst, total):
    sum = 0
    for element in lst:
        sum += element
        all_possible_combinations = set(itertools.product(lst, repeat=2)) # This prints all possible combinations of the elements in the list with length of 2
        for items in all_possible_combinations:
            a = 0
            for i in items:
                a += i
            if a == total:
                x = items
    print(x)
    print('These are all combinations:', all_possible_combinations)

fun([0, 1, 2], 2)

This programme only returns one of the lists

>>>>>>>>>
(0, 2)
>>>>>>>>>

How do I correct this? I am expecting the final result to be

>>>>>>>>>
(2, 0)
(1, 1)
(0, 2)
>>>>>>>>>

Solution

  • If I understand your code correctly you just keep overwriting the values, leaving you only the last value of x. Creating an array and appending the items to this array should show all results.

    import itertools
    
    def fun(lst, total):
        sum = 0
        for element in lst:
            sum += element
            x = []
            all_possible_combinations = set(itertools.product(lst, repeat=2)) # This prints all possible combinations of the element in the list with length of 2
            for items in all_possible_combinations:
                a = 0
                for i in items:
                    a += i
                if a == total:
                    x.append(items)
        print(x)
        print('These are all combinations:', all_possible_combinations)
    
    fun([0, 1, 2], 2)