Question: Problem 2b sums.py: Cumulative sum Write a function cumsum() that takes a list l as argument and returns the cumulative sum (also known as the
Problem 2b sums.py: Cumulative sum
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, youll have to write a loop that runs two accumulations in tandem. The first is the standard sum-so-far that weve 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
Here is my code
def altsum(l, init=0): total = init for i in range(0,len(l)): if i % 2 == 0: total += l[i] else: total -= l[i] return total def cumsum(l): cs = [] for i in range(len(l)): sum = 0 for j in range(i + 1): sum = sum + l[j] cs.append(sum) return cs import sys # The following code is provided for your convenience only if __name__ == '__main__': l = [] for arg in sys.argv[1:]: l.append(int(arg)) if 'altsum' in globals(): print "Alternating sum:", altsum(l) if 'cumsum' in globals(): print "Cumulative sum: ", cumsum(l)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
