2013-05-01 29 views
-5
enter code here 
"""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 list(l): 
new_l = [] 
j = 0 
for i in l: 
    for i in range(l.index(i)+1): 
    j += l[i] 
    new_l.append(j) # this for loop seems to accumulate twice 
return new_l 

print list([1,2,3,4]) # [1,4,10,20] other than [1,3,4,10] 

就是这样。感谢您通过打印[1,3,4,10]使其工作的答案!请帮我解决一下我的Python代码基础知识:'for'循环列表和累积和

+0

我想你是指'[1,3,6,10]'。 – 2013-05-01 09:41:48

回答

1

提高您的解决方案,你并不需要2 for循环的位置:

def lis(l): 
new_l = [] 
j = 0 
for i in range(len(l)): 
     j += l[i] 
     new_l.append(j) 
return new_l 

print lis([1,2,3,4]) #prints [1, 3, 6, 10] 

这是更好地使用发电机的功能在这里:

def cumulative(lis): 
    summ=0 
    for x in lis: 
     summ+=x 
     yield summ 
    ....:   

In [48]: list(cumulative([1,2,3])) 
Out[48]: [1, 3, 6] 

或py3x使用itertools.accumulate

In [2]: from itertools import accumulate 

In [3]: list(accumulate([1,2,3])) 
Out[3]: [1, 3, 6] 
+0

感谢您的全面回答。 – 2013-05-01 02:32:22

0

你不需要两个循环。这里是一个简单的程序解决方案:

def running_sums(numbers): 
    result = [] 
    total = 0 
    for n in numbers: 
    total = total + n 
    result.append(total) 
    return result 
+0

请勿使用'sum'作为变量名称。 – 2013-05-01 02:31:32

+0

在这样的小片段中看起来非常无害,您可以一眼看到所有用途,并告诉它它不是库函数,但足够公平。改变。 – 2013-05-01 02:43:03

+0

@Mark Reed谢谢 – 2013-05-01 03:13:29

0

list是名称为您的功能一个糟糕的选择,因为它阴影内置的list。你的问题是你没有为每个新元素重置j0。使用l作为变量名称也气馁,因为它看起来像在某些字体

def do_list(l): 
    new_l = [] 
    for i in l: 
     j = 0   # <== move this line here 
     for i in range(l.index(i)+1): 
      j += l[i] 
     new_l.append(j) 
    return new_l 

看它的另一种方式1,是摆脱内环的,只是每次添加当前项目以

def do_list(l): 
    new_l = [] 
    j = 0   
    for i in l: 
     j += i 
     new_l.append(j) 
    return new_l 
+0

惊人的答案,虽然基于我不那么简短的代码。谢谢! – 2013-05-01 02:43:44