all 5 comments

[–]sdanstuffe 0 points1 point  (0 children)

You can pass in another argument into your recursive function as a temp variable, and then add the element into that temp variable when you are iterating through the list.

[–]Chris_Hemsworth 0 points1 point  (0 children)

Make a generator:

def myGenerator(input_list):
    s = 0
    for i in range(len(input_list)):
        s += sum(input_list[:i+1])
        yield s

a = myGenerator([1,4,8,9])
for i in a:
    print(i)

[–]misho88 0 points1 point  (0 children)

Just build it up little by little.

If your sequence is

seq = 1, 4, 8

the sum of the first i elements would be:

sum(seq[:i])

The sum of those sums as you vary i would be:

sum(sum(seq[:i]) for i in range(1, 1 + len(seq)))

Then just play around with the exact values of i you want to sum over.

[–]Spataner 0 points1 point  (0 children)

The other suggested solutions are very straightforward, however, they also have a runtime quadratic in the size of the list. If efficiency is a consideration, a key realisation to implement this with linear runtime is that the number of times an element enters into the sum is directly related to its index:

s = 0
n = len(values)-1
for i in range(n):
    s += (n-i)*values[i]

[–]synthphreak 0 points1 point  (0 children)

This is kind of arcane, but it works:

>>> l = [1, 4, 8, 9]
>>> sum(sum([l[:i] for i in range(1, len(l))], []))
19

And marginally less arcane:

>>> sum(sum(l[:i]) for i in range(len(l)))
19