Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

Cummulative sum with a python list

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could try a for loop:

hist = [0, 1, 2, 3, 4]
cumulative_sum = []
c = 0
for i in hist:
    c += i
    cumulative_sum.append(c)
print(cumulative_sum)

Or try a list comprehension as follows:

print([sum(hist[:i + 1])for i in range(len(hist))])

Both codes output:

[0, 1, 3, 6, 10]

Edited:

As the OP mentioned he doesn't want a for loop, so try this function:

def cumulative_sum(hist, initial_sum):
    if hist:
        return [hist[0] + initial_sum] + cumulative_sum(hist[1:], hist[0] + initial_sum)
    else:
        return []
    
print(cumulative_sum([2, 3, 5, 4], 7))

Output:

[9, 12, 17, 21]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...