Find all possible subsets that sum up to a given number

前端 未结 4 684
既然无缘
既然无缘 2021-01-21 20:32

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

4条回答
  •  渐次进展
    2021-01-21 20:38

    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

提交回复
热议问题