Question

Python 2.7 Write a function cumsum() that takes a list l as argument and returns the...

Python 2.7

Write a function cumsum() that takes a list l as argument and returns the cumulative sum (also known as the prefix sum) of l, which is a list, say cs of the same length as l such that each element cs[i] is equal to the sum of the first i + 1 elements of l, i.e.,

cs[i] == l[0] + l[1] + l[2] + ... + l[i]

You should not modify the argument list l in any way. Also, you do not need to assume that l contains numbers; your function should work with any elements that support +. Practice goal: Although not required, try to solve this without using a nested loop. In this case, you’ll have to write a loop that runs two accumulations in tandem. The first is the standard sum-so-far that we’ve seen several times. The second is an accumulation of the intermediate sum-so-far values into a list (e.g., via an .append() operation); the final value of this list is the desired result.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

def cumsum(l):
if all(isinstance(item, int) for item in l) or all(isinstance(item, float) for item in l):
     list = []
     for i in range(len(l)):
         sum = 0;
         for j in range(i+1):
             sum = sum + l[j]
         list.append(sum)
else:
     list = []
     for i in range(len(l)):
         str = "";
         for j in range(i+1):
             str = str + l[j]
         list.append(str)
return list

l1 = [1,2,3,5]
l2 = [2.3, 4.5, 6.7,5.6]
l3 = ['a','b','c','d']
print(cumsum(l1))
print(cumsum(l2))
print(cumsum(l3))

Add a comment
Know the answer?
Add Answer to:
Python 2.7 Write a function cumsum() that takes a list l as argument and returns the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT