I deduct that if your 'iteration version works flawlessly' then objective is:
[1,0,2,0,0,3,1,3,2,1] --> [13, 12, 12, 10, 10, 10, 7, 6, 3, 1]
I think that your solution is too complicated.
Lists support sum(), so:
EDIT: how Python core developers do it
There is built-in module itertools which have function accumulate (Make an iterator that returns accumulated sums).
There is rough equivalent provided:
[1,0,2,0,0,3,1,3,2,1] --> [13, 12, 12, 10, 10, 10, 7, 6, 3, 1]
I think that your solution is too complicated.
Lists support sum(), so:
>>> sum([1, 2]) 3Lists also support slicing:
>>> a = [1, 2, 3, 4, 5] >>> a[1:] [2, 3, 4, 5] >>> sum(a[1:]) 14Combining those two things into list comprehension and taking into account noisefloor comment about Python antipattern you can write simply:
>>> a = [1,0,2,0,0,3,1,3,2,1] >>> [sum(a[i:]) for i, v in enumerate(a)] [13, 12, 12, 10, 10, 10, 7, 6, 3, 1]Iterative solution should give you pretty good idea how to proceed with recursive solution.
EDIT: how Python core developers do it
There is built-in module itertools which have function accumulate (Make an iterator that returns accumulated sums).
There is rough equivalent provided:
def accumulate(iterable, func=operator.add): 'Return running totals' # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 it = iter(iterable) try: total = next(it) except StopIteration: return yield total for element in it: total = func(total, element) yield total
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.