Creating an array of numbers that sum to a given number

前端 未结 2 621
我在风中等你
我在风中等你 2020-12-17 03:19

I\'ve been working on some quick and dirty scripts for doing some of my chemistry homework, and one of them iterates through lists of a constant length where all the element

2条回答
  •  情歌与酒
    2020-12-17 03:54

    Generic, recursive solution:

    def get_lists_with_sum(length, my_sum):
        if my_sum == 0:
            return [[0 for _ in range(length)]]
    
        if not length:
            return [[]]
        elif length == 1:
            return [[my_sum]]
        else:
            lists = []
            for i in range(my_sum+1):
                rest = my_sum - i
                sublists = get_lists_with_sum(length-1, rest)
                for sl in sublists:
                    sl.insert(0, i)
                    lists.append(sl)
    
        return lists
    
    print get_lists_with_sum(11, 8)
    

提交回复
热议问题