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

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

问题描述

我想编写一个函数,该函数接受一个数字列表并返回累加的总和;也就是说,一个新列表,其中ith元素是原始列表中前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].

到目前为止,这是我的代码:

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

但是,它不起作用.

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

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

推荐答案

您可能对此过程有点过分考虑.逻辑并不需要真正地分解成这样的案例测试.到目前为止,您拥有的部分是总计数器,但是您只需要遍历列表中的每个值.不使用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天全站免登陆