条件while循环来计算累积总和? [英] Conditional while loop to calculate cumulative sum?

查看:38
本文介绍了条件while循环来计算累积总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数,它接受一个数字列表并返回累积和;也就是说,一个新列表,其中第 i 个元素是原始列表中前 i+1 个元素的总和.例如[1, 2, 3]的累计和为[1, 3, 6].

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].

这是我目前的代码:

 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])

但是,它不起作用.

你能告诉我我做错了什么吗?我已经为此工作了一段时间.

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

推荐答案

您可能对这个过程想得有点多.逻辑不需要真正拆分成这样的案例测试.到目前为止,您正确的部分是总计数器,但您应该只需要遍历列表中的每个值.不做条件 while,用 if..else

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

我们仍然使用总计数器.我们为我们的结果创建一个空列表.但是我们所要做的就是遍历列表中的每个项目,添加到总数中,然后每次附加新值.没有条件,您不必担心 while 何时会中断.您将循环遍历原始列表中的每个项目是一致的.

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.

这篇关于条件while循环来计算累积总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆