Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all possible subsets that sum up to a given number

I'm learning Python and I have a problem with this seems to be simple task.

I want to find all possible combination of numbers that sum up to a given number.
for example: 4 -> [1,1,1,1] [1,1,2] [2,2] [1,3]

I pick the solution which generate all possible subsets (2^n) and then yield just those that sum is equal to the number. I have a problem with the condition. Code:

def allSum(number):
    #mask = [0] * number
    for i in xrange(2**number):
        subSet = []
        for j in xrange(number):
            #if :
                subSet.append(j)
        if sum(subSet) == number:
           yield subSet



for i in allSum(4):
    print i   

BTW is it a good approach?

like image 791
Lukasz Madon Avatar asked Feb 02 '26 05:02

Lukasz Madon


1 Answers

Here's some code I saw a few years ago that does the trick:

>>> def partitions(n):
        if n:
            for subpart in partitions(n-1):
                yield [1] + subpart
                if subpart and (len(subpart) < 2 or subpart[1] > subpart[0]):
                    yield [subpart[0] + 1] + subpart[1:]
        else:
            yield []

>>> print list(partitions(4))
[[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]]

Additional References:

  • http://mathworld.wolfram.com/Partition.html
  • http://en.wikipedia.org/wiki/Partition_(number_theory)
  • http://www.site.uottawa.ca/~ivan/F49-int-part.pdf
like image 154
Raymond Hettinger Avatar answered Feb 03 '26 22:02

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!