Home > Net >  Prints a sub-list where the sum of its elements is the same as the sum of all the elements of the or
Prints a sub-list where the sum of its elements is the same as the sum of all the elements of the or

Time:03-08

I have to write a Python code that when given a list of numbers, prints a sub-list where the sum of its elements is the same as the sum of all the elements of the original list. For example, considering the list of numbers [5, 6, 8, 6, 6, -12], the code should print the sub-list [5,6,8] since both original and sub-list elements have a sum value equal to 19; for the list

So far I’ve done:

list_1 = [5, 6, 8, 6, 6, -12]
sub_list = []

for i in list_1:
    sub_list.append(i)
    if sum(sub_list) == sum(list_1):
        sub_list.remove(i)
    for i in list_1:
        if sum(sub_list) == sum(list_1):
            sub_list.remove(i)

print(sub_list)

CodePudding user response:

If lst is your list of numbers then:

def get_sublist(lst):
    tot = sum(lst)
    for i in range(len(lst)):
        for j in range(i   1, len(lst)   1):
            sub_lst = lst[i:j]
            if sum(sub_lst) == tot:
                return sub_lst

sub_lst = get_sublist(lst)

This code generates every possible sublist, computes their sum and compares it with the sum of the entire list.

The complexity is not optimal, i.e. there are faster algorithms to solve this problem out there. For example, you don't need to compute the sum of the entire sublist every time you add a new element to it...

  • Related