The task of creating a prefix sum list in Python involves iterating over a sequence of numbers and calculating the cumulative sum at each index. For example, with a list of numbers a = [3, 4, 1, 7, 9, 1], the task is to compute the cumulative sum at each index, resulting in a prefix sum list like [3, 7, 8, 15, 24, 25].
Using for loop
For loop compute a prefix sum is the most efficient approach. It involves iterating through the array and maintaining a running sum that is updated at each index. The cumulative sum is appended to a new list. This method only requires a single pass through the list, making it both time and space efficient.
Python
a = [3, 4, 1, 7, 9, 1]
res = []
cur_s= 0 # current sum
for num in a:
cur_s += num
res.append(cur_s)
print(res)
Output[3, 7, 8, 15, 24, 25]
Explanation : for loop iterates over each element in the list a, adding the current element num to cur_s. After updating cur_s, the new cumulative sum is appended to the list res.
Using numpy
NumPy provides a highly optimized method for computing prefix sums using the np.cumsum() function. This method leverages low-level, highly efficient vectorized operations to compute the cumulative sum of an array. It is ideal for handling large datasets due to its speed and memory efficiency.
Python
import numpy as np
a = [3, 4, 1, 7, 9, 1]
res = np.cumsum(a)
print(res)
Explanation : np.cumsum() computes the cumulative sum of the list a efficiently using NumPy's vectorized operations. The result, stored in res, contains the prefix sums of the elements in a.
itertools.accumulate() is a simple and elegant way to compute prefix sums. It returns an iterator that yields accumulated results, making it memory-efficient as it computes the cumulative sum on the fly. This method is useful when we don't want to store the entire list at once.
Python
import itertools
a = [3, 4, 1, 7, 9, 1]
res = list(itertools.accumulate(a))
print(res)
Output[3, 7, 8, 15, 24, 25]
Explanation: itertools.accumulate() computes the cumulative sum of a efficiently, returning an iterator that yields the prefix sums, which are then converted to a list and stored in res.
Using list comprehension
list comprehension approach to computing prefix sums is a concise but inefficient method. It sums the elements of the list up to each index in a new list. While easy to implement, this method recalculates the sum for each element from scratch, making it less efficient for large datasets.
Python
a = [3, 4, 1, 7, 9, 1]
res = [sum(a[:i+1]) for i in range(len(a))]
print(res)
Output[3, 7, 8, 15, 24, 25]
Explanation: list comprehension calculates the prefix sum by summing elements of a up to each index i.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice