Pergunta

I want to write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].

Here is my code so far:

 def count(list1):
     x = 0
     total = 0
     while x < len(list1):
         if x == 0:
             total = list1[0]
             print total
             x = x +1
         else:
             total = list1[x] + list1[x -1]
             print total
             x = x + 1
     return total 

print count([1, 2, 3, 4, 7])

However, it is not working.

Can you tell me what I am doing wrong? I worked on this for quite some time now.

Foi útil?

Solução

You might be over-thinking the process a bit. The logic doesn't need to really be split up into case tests like that. The part you have right so far is the total counter, but you should only need to loop over each value in the list. Not do a conditional while, with if..else

Normally I wouldn't just give an answer, but I feel its more beneficial for you to see working code than to try and go through the extra and unnecessary cruft you have so far.

def count(l):
    total = 0
    result = []
    for val in l:
        total += val
        result.append(total)
    return result

We still use the total counter. And we create an empty list for our results. But all we have to do is loop over each item in the list, add to the total, and append the new value each time. There are no conditionals and you don't have to worry about when a while is going to break. It's consistant that you will loop over each item in your original list.

Outras dicas

Here you are adding the current index with the last one and overriding "total"

total = list1[x] + list1[x -1]

I guess you want something like this, it will return 31 for the list below.

def count(list1):
     x = 0
     total = 0
     while x < len(list1):
         total += list[x]
         print total
         x = x + 1
     return total

list = [1, 2, 4, 8, 16]
print count(list)

One simple approach can be

>>> given_list = [1, 4, 5, 8]
>>> output_list = [sum(given_list[:num]) for num in range(len(given_list)+1)]
>>> output_list
[0, 1, 5, 10, 18]
>>> output_list[1:]
[1, 5, 10, 18]
>>> 

See if this works for different kind of list. I leave that for you.

You're not doing exactly what you want to be doing with total.

What you're setting total to is list[x] + list[x+1]. You really want it to be the sum of all previous elements and the current element.

Replace total = list1[x] + list1[x-1] with total += list1[x].

You don't need to write this function. It's placed in the itertools module:

>>> list(itertools.accumulate([1,2,3]))
[1, 3, 6]

This is the solution I came up with:

def count(list1):
     total = 0
     old = 0
     for position, x in enumerate(list1):
         total = x + old
         old = x
         print total
     return


count([1,1,2,3,5,8,13])

Another solution, one-liner, but definitely working ( http://ideone.com/qtwh7), even though multi-line solutions are clearer on what really happens here:

data = [3, 7, 22, -3, 5, -23, 16]

result = reduce(lambda a, b: a+[a[-1]+b], data, [0])[1:]

print result

I did the same exercise, and what follows is my solution. It uses only the basic append list method and the slice list operator.

def accum(list):
    """Sequential accumulation of the original list"""
    result = []
    for i in range(len(list)):
        result.append(sum(list[:i+1]))
    return result
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top