Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sums of Parts Python 3

Let us consider this example (array written in general format):

ls = [0, 1, 3, 6, 10]

Its following parts:

ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []

The corresponding sums are (put together in a list): [20, 20, 19, 16, 10, 0]

The function parts_sums (or its variants in other languages) will take as parameter a list ls and return a list of the sums of its parts as defined above.

I have tried like this but is not executed in given Execution Time.How can I speed up this code:

def parts_sums(ls):
    sums=[]
    if len(ls)==0:
        return[0]
    else:
        while len(ls)!=0:
            sums.append(sum(ls))
            ls.pop(0)
        sums.append(0)
        return sums
like image 809
Aditya M.S Avatar asked Dec 10 '25 23:12

Aditya M.S


1 Answers

Here's an iterative, O(n) solution.

def parts_sums(ls):
    sums = [0] * (len(ls) + 1)
    for i, e in enumerate(reversed(ls)):
        sums[len(ls) - i - 1] += sums[len(ls) - i] + e
    return sums
like image 192
M Z Avatar answered Dec 13 '25 12:12

M Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!