recursive cumulative sums

Posted by user1816377 on Stack Overflow See other posts from Stack Overflow or by user1816377
Published on 2012-11-12T16:30:13Z Indexed on 2012/11/12 17:00 UTC
Read the original article Hit count: 135

Filed under:

I need to write a program that compute cumulative sums from a list of numbers with def but ONLY with recursion. I did it, but now I need to write the same program without using the method sum, but no success so far. Any idea?

my code:

def rec_cumsum(numbers):
        ''' Input: numbers - a list of numbers,
                Output: a list of cumulative sums of the numbers'''
        if len(numbers)==0: return numbers

        return rec_cumsum(numbers[:-1])+ [sum(numbers)]

input:

1 [1,2,3]

2 [2, 2, 2, 3]

output:

1 [1,3,6]

2 [2, 4, 6, 9]

© Stack Overflow or respective owner

Related posts about python