Creating an array of numbers that sum to a given number

前端 未结 2 620
我在风中等你
我在风中等你 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:38

    Here's a recursive generator that yields the lists in lexicographic order. Leaving exact as True gives the requested result where every sum==limit; setting exact to False gives all lists with 0 <= sum <= limit. The recursion takes advantage of this option to produce the intermediate results.

    def lists_with_sum(length, limit, exact=True):
        if length:
            for l in lists_with_sum(length-1, limit, False):
                gap = limit-sum(l)
                for i in range(gap if exact else 0, gap+1):
                    yield l + [i]
        else:
            yield []
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题