algorithm to sum up a list of numbers for all combinations

前端 未结 15 2296
北荒
北荒 2020-12-04 22:34

I have a list of numbers and I want to add up all the different combinations. For example:

  • number as 1,4,7 and 13
  • the output would be:

15条回答
  •  难免孤独
    2020-12-04 23:09

    v=[1,2,3,4]#variables to sum
    i=0
    clis=[]#check list for solution excluding the variables itself
    def iterate(lis,a,b):
        global i
        global clis
        while len(b)!=0 and i1:
                t=a+sum(b)
                clis.append(t)
            for j in b:
                clis.append(a+j)
            i+=1
            iterate(lis,a,b)
    iterate(v,0,v)
    

    its written in python. the idea is to break the list in a single integer and a list for eg. [1,2,3,4] into 1,[2,3,4]. we append the total sum now by adding the integer and sum of remaining list.also we take each individual sum i.e 1,2;1,3;1,4. checklist shall now be [1+2+3+4,1+2,1+3,1+4] then we call the new list recursively i.e now int=2,list=[3,4]. checklist will now append [2+3+4,2+3,2+4] accordingly we append the checklist till list is empty.

提交回复
热议问题