Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

python - Creating an array of numbers that sum to a given number

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 elements sum to a given constant. For each, I check if they meet some additional criteria and tack them on to another list.

I figured out a way to meet the sum criteria, but it looks horrendous, and I'm sure there's some type of teachable moment here:

# 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...