Question: Python Problem Problem 2a sums.py: Alternating sum [5 points] Write a function altsum() that takes a list l and a value init as argument and
Python Problem
Problem 2a sums.py: Alternating sum [5 points]
Write a function altsum() that takes a list l and a value init as argument and returns the alternating-sign sum init + l[0] - l[1] + l[2] - l[3] + l[4] - l[5] + .... starting with initial value init and then going up to the last element of l. If l is empty, you should trivially return init. Finally, the init argument should have a default value of 0.
Practice goal: Simple accumulation loop, over a list. Default argument values.
Problem 2b sums.py: Cumulative sum [10 points]
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
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
