Here is a simple generator-based implementation:
def cumsum(seq): s= 0 for c in seq: s+= c yield s print [c for c in cumsum(range(7))] print [c for c in cumsum((0, 1, 2, 3, 4, 5, 6))]
This IMHO is quite Putin's way of implementing cumsum.
But here is a more pragmatic implementation that allows you to process (all) all types where adding can make sense.
def cumsum(seq): s= seq[0] for k in xrange(1, len(seq)): yield s s= s+ seq[k] yield s print [c for c in cumsum(range(7))] print [c for c in cumsum((0, 1, 2, 3, 4, 5, 6))] print [c for c in cumsum(['a', 'b', 'c'])] print [c for c in cumsum([['a'], ['b'], ['c']])] print [c for c in cumsum((('a', ), ('b', ), ('c', )))]
Thus, all these examples behave as expected, which is not true for the Pythonic version. Try it yourself and find out the reason for the different behavior.
Update:
Based on the comments, there will be a more general cumsum:
def cumsum(iterable): iterable= iter(iterable) s= iterable.next() yield s for c in iterable: s= s+ c yield s tests= [ [], [1], [1, 2], range(7), (0, 1, 2, 3, 4, 5, 6), ['a', 'b', 'c'], [['a'], ['b'], ['c']], (('a', ), ('b', ), ('c', )), xrange(7), ] for test in tests: print test, '=> ', list(cumsum(test))
Two more exits, but IMHO it is still very readable. And now the implementation focuses on what type of the first element iterable dictates, as expected that the addition will behave with the rest of the elements.