-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] 使其工作的答案!

4

3 回答 3

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]
于 2013-05-01T02:19:35.750 回答
0

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

def running_sums(numbers):
  result = []
  total = 0
  for n in numbers:
    total = total + n
    result.append(total)
  return result
于 2013-05-01T02:29:21.230 回答
0

list为您的函数命名是一个错误的选择,因为它会影响内置函数list。您的问题是您没有j0每个新元素重置。也不鼓励l用作变量名,因为它1在某些字体中看起来像

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

另一种看待它的方法是摆脱内部循环,每次都将当前项目添加到其中

def do_list(l):
    new_l = []
    j = 0           
    for i in l:
        j += i
        new_l.append(j)
    return new_l
于 2013-05-01T02:30:12.260 回答