Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

python - Conditional while loop to calculate cumulative sum?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...