Get all numbers that add up to a number

后端 未结 4 1058
情深已故
情深已故 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:04

    There's a snippet here:

    from itertools import combinations, chain
    
    def sum_to_n(n):
        'Generate the series of +ve integer lists which sum to a +ve integer, n.'
        from operator import sub
        b, mid, e = [0], list(range(1, n)), [n]
        splits = (d for i in range(n) for d in combinations(mid, i)) 
        return (list(map(sub, chain(s, e), chain(b, s))) for s in splits)
    

    Use it like this:

    for p in sum_to_n(4):    
        print p
    

    Outputs:

    [4]
    [1, 3]
    [2, 2]
    [3, 1]
    [1, 1, 2]
    [1, 2, 1]
    [2, 1, 1]
    [1, 1, 1, 1]
    

提交回复
热议问题