Creating an array of numbers that add up to a given number

I worked on some quick and dirty scripts to do my homework in chemistry, and one of them iterates through constant-length lists, where all the elements are summed with a given constant. For each, I check whether they meet some additional criteria and bind them to another list.

I figured out a way to meet the criteria for the amount, but it looks awful, and I'm sure there is some learning point:

# iterate through all 11-element lists where the elements sum to 8.
for a in range(8+1):
 for b in range(8-a+1):
  for c in range(8-a-b+1):
   for d in range(8-a-b-c+1):
    for e in range(8-a-b-c-d+1):
     for f in range(8-a-b-c-d-e+1):
      for g in range(8-a-b-c-d-e-f+1):
       for h in range(8-a-b-c-d-e-f-g+1):
        for i in range(8-a-b-c-d-e-f-g-h+1):
         for j in range(8-a-b-c-d-e-f-g-h-i+1):
            k = 8-(a+b+c+d+e+f+g+h+i+j)
            x = [a,b,c,d,e,f,g,h,i,j,k]
            # see if x works for what I want
+5
source share
2 answers

, . exact True , == limit; exact False 0 <= sum <= limit. .

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 []
+1

, :

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)
+1

All Articles