I have to make myself a recursive function : cumulative_sum(hist,initial_sum)
, I'll explain myself with an example it will be more comprehensive:
hist=[0,1,2,3,4]
, initial=0
cumulative_sum
need to return [0+0(the first is initial sum),0+0+1,0+0+1+2,0+0+1+2+3,0+0+1+2+3+4]
=[0,1,3,6,10]
second exemple:
hist=[2,4,5,3], initial_sum=7
return [2+7,2+7+4,2+7+4+5,2+7+4+5+3]
i can't change the parameters of cumulative_sum and can't change the list hist
i tried this but my prog did'nt return anything:
def cumulative_sum(hist, initial_sum=0):
if len(hist)==0:
new=[]
return new.append(hist[0]+initial_sum)
return cumulative_sum(hist[1:],new[-1])
this second prog was doing th job but my teacher tell me that i can't use a global variable (new)
new = []
def cumulative_sum(hist, initial_sum=0):
if len(hist) == 0:
return new
new.append(hist[0] + initial_sum)
return cumulative_sum(hist[1:], new[-1])
thanks for your help if you got some idea i'm here!!
question from:
https://stackoverflow.com/questions/65650790/cummulative-sum-with-a-python-list 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…