Rylai Crestfall
Rylai Crestfall

Reputation: 91

Subset Sum with Backtracking on Python

So I want to print out all the subsets of the initial set that will add up to 21. So far I've only come up with this

def twentyone(array, num=21):
    if len(array) == 0:
        return None
    else:
        if array[0] == num:
            return [array[0]]
        else:
            with_v = twentyone(array[1:], (num - array[0]))
            if with_v:
                return [array[0]] + with_v
            else:
                return twentyone(array[1:], num)

It does give the solution, but only the first. How do I change it so that it will give me every possible subset. I've tried making a few changes but it only gives me nested lists. Any help would be nice.

Upvotes: 1

Views: 5151

Answers (2)

JuniorCompressor
JuniorCompressor

Reputation: 20015

You can create a recursive generator:

def twentyone(array, num=21):
    if num < 0:
        return
    if len(array) == 0:
        if num == 0:
            yield []
        return
    for solution in twentyone(array[1:], num):
        yield solution
    for solution in twentyone(array[1:], num - array[0]):
        yield [array[0]] + solution

Example:

>>> list(twentyone([5, 16, 3, 2]))
[[16, 3, 2], [5, 16]]

Upvotes: 4

Selcuk
Selcuk

Reputation: 59184

If you are allowed to use standard Python libraries, here is a shorter solution:

import itertools
import operator


def twentyone(array, num=21):
    subsets = reduce(operator.add, [list(itertools.combinations(array, r)) for r in range(1, 1 + len(array))])
    return [subset for subset in subsets if sum(subset) == num]


print twentyone([1, 2, 5, 6, 8, 9, 10])

result:

[(2, 9, 10), (5, 6, 10), (1, 2, 8, 10), (1, 5, 6, 9), (2, 5, 6, 8)]

Upvotes: 1

Related Questions