2013-05-01 1 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]을 인쇄 해 주셔서 감사합니다! 여기에 루프 -파이썬 기본을위한 코드를 수정하는 데 도움을주십시오. 'for'루프가 누적 합계

+0

나는 [1,3,6,10]을 (를) 의미한다고 생각합니다. –

답변

1

솔루션을 개선, 당신이 필요하지 않습니다 :

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] 

또는 itertools.accumulate py3x 사용 :

In [2]: from itertools import accumulate 

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

종합적인 답변을 보내 주셔서 감사합니다. –

0

두 개의 루프가 필요하지 않습니다. 여기에 간단한 절차 솔루션이다 : 그것은 내장 list 그림자로

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

'sum'을 변수 이름으로 사용하지 마십시오. –

+0

모든 용도를 한눈에 볼 수 있고 라이브러리 기능이 아니라는 것을 알 수있는이 작은 조각에서 꽤 해가없는 것 같습니다. 변경됨. –

+0

@ 마크 리드 감사합니다 –

0

list은 함수의 이름의 나쁜 선택이 될 것입니다. 문제는 각 새 요소에 대해 j0으로 재설정하지 않는 것입니다. 그것은 어떤 글꼴

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처럼 보이는 변수 이름도 낙심 될 때 l를 사용하여 내부 루프를 제거하는 것입니다, 단지마다 그것을 현재의 항목을 추가

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

놀라운 대답, 비록 내 간단한 코드를 기반으로. 고맙습니다! –