Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prints a sub-list where the sum of its elements is the same as the sum of all the elements of the original list

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 = [4, 5, 7, 5, 5, -10]
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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If lst is your list of numbers then:

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:
            print(sub_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…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading