How can we implement this function in Python? Studying this will not only show you how the NumPy cumsum function works, but it’ll also make you a better coder because it contains many important concepts in computer science (such as recursion).
Here’s the NumPy cumsum function in Python code (without using the NumPy library):
def cumsum(l:list): if not l: return  sums =  sums.append(l) return helper(sums, l[1:]) def helper(sums:list, xs:list): if not xs: return sums s = sums[len(sums) - 1] sums.append(s + xs) if len(xs) > 1: return helper(sums, xs[1:]) return sums xs =  print(cumsum(xs)) # xs = [1, 3, 3, 2, 5] print(cumsum(xs)) # [1, 4, 7, 9, 14] xs = [1, 1, 1, 2] print(cumsum(xs)) # [1, 2, 3, 5]
The functions in this code snippet compute a list of sums from the values of the input list. In the output list at index
j there is the sum of
sums[j-1] + input[j].
This is done in a recursive way. The cumsum function only starts the recursion by putting the first element of the input list in the first position of the output list and then it starts the recursion with the helper-function by passing the lists sums and
xs[1:]. Note that in each recursion step the
xs list is shorter because we slice off the first element each time.
With the given input
[1, 1, 1, 2] we compute the output
[1, 1+1, 1+1+1, 1+1+1+2] = [1, 2, 3, 5].
Where to Go From Here
Want to dive deeper into the ins and outs of the NumPy library? If you have any ambition in data science or machine learning, you should. NumPy is the most important library to learn in the Python ML and data science area!
Read my book “Coffee Break NumPy” to experience a fun way of mastering NumPy—based on the popular puzzle-based learning technique. Everything else in data science will be much easier after you’ve mastered NumPy!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.