Making a list of sums of subsets of a list

Viewed 64

We have a list say list1 = [2, 1, 4]

I made a 2d list called subl of the subsets of list1 with following code.

def sub_lists(list1):
    sublist = [[]]
    for i in range(0, len(list1) - 1):
        for j in range(i + 1, len(list1) + 1):
            sub = list1[i:j]
            sublist.append(sub)
    return sublist

The output I got is

subl = sub_lists(list1) #[[], [2], [2, 1], [2, 1, 4], [1], [1, 4]]

Now I want to make an array of sums of the list elements present in in subl I wrote following code but its not working correctly.

sum = [];
for i in range(0, len(subl) - 1):
  l = len(subl[i])
  t = 0
  for j in range(0, l - 1):
    t = t + subl[i][j]
  sum.append(t)
print(sum)

The output I'm getting is

[0, 0, 2, 3, 0]

While the desired output should be

[0,2,3,7,1,5]

I guess there's something wrong in the second for loop. Please help!

3 Answers

The reason isn't working is because you are looping up to i=len(subl)-2 and j=l-2, which makes that the last element isn't counted, so you can change both loops to for i in range(0, len(subl)): and for j in range(0, l):. Also, as a suggestion, don't use sum as a variable name because it's a built in function in python and it can yield errors. So, the corrected code will be:

list1 = [2, 1, 4]
def sub_lists(list1):
    sublist = [[]]
    for i in range(0, len(list1) - 1):
        for j in range(i + 1, len(list1) + 1):
            sub = list1[i:j]
            sublist.append(sub)
    return sublist

subl=sub_lists(list1)
s=[];
for i in range(0, len(subl)):
    l=len(subl[i])
    t=0;
    for j in range(0, l):
        t=t+subl[i][j]
    s.append(t)
print(s)

As a suggestion, you could use map and sum

list1 = [2, 1, 4]
def sub_lists(list1):
    sublist = [[]]
    for i in range(0, len(list1) - 1):
        for j in range(i + 1, len(list1) + 1):
            sub = list1[i:j]
            sublist.append(sub)
    return sublist

subl=sub_lists(list1)
s=list(map(sum, subl))
#same as [sum(l) for l in subl]
print(s)

Or just add the sum as @deadshot said, if your principal purpose is the sum of the sublists:

list1 = [2, 1, 4]
def sum_of_sublists(list1):
    sublist = [0]
    for i in range(0, len(list1) - 1):
        for j in range(i + 1, len(list1) + 1):
            sub = list1[i:j]
            sublist.append(sum(sub))
    return sublist

print(sum_of_sublists(list1))

All outputs:

[0,2,3,7,1,5]

Your code doesn't work because your ranges are incorrect, use respectively range(0, len(subl)) and range(0, l)

import numpy as np
list1 = [2, 1, 4]
subl = sub_lists(list1)

You could just use list comprehension to find the sum of sub lists :

ans = [int(np.sum(l)) for l in subl]

Output :

ans # prints [0, 2, 3, 7, 1, 5]
Related