Creating an array of numbers that sum to a given number

前端 未结 2 622
我在风中等你
我在风中等你 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 []
    

提交回复
热议问题