Get all numbers that add up to a number

后端 未结 4 1059
情深已故
情深已故 2020-12-02 23:50

I\'m trying to find a way to display all the possible sets of X integers that add up to a given integer. for example to get all 2 integer sets that make 5 I would have:

4条回答
  •  不思量自难忘°
    2020-12-03 00:19

    Here is one way to solve this problem:

    def sum_to_n(n, size, limit=None):
        """Produce all lists of `size` positive integers in decreasing order
        that add up to `n`."""
        if size == 1:
            yield [n]
            return
        if limit is None:
            limit = n
        start = (n + size - 1) // size
        stop = min(limit, n - size + 1) + 1
        for i in range(start, stop):
            for tail in sum_to_n(n - i, size - 1, i):
                yield [i] + tail
    

    You can use it like this.

    for partition in sum_to_n(6, 3):
        print partition
    
    [2, 2, 2]
    [3, 2, 1]
    [4, 1, 1]
    

提交回复
热议问题