python-cheatsheet icon indicating copy to clipboard operation
python-cheatsheet copied to clipboard

added cumulative sum for list

Open reyadussalahin opened this issue 3 years ago • 0 comments

sometimes we need to calculate cumulative sum for a list as follows:

def get_cumulative_sum(num_list: List[int]) -> List[int]:
    cumulative_sum = [0] * len(num_list)
    for i, v in enumerate(num_list):
        cumulative_sum[i] = v + (0 if i == 0 else cumulative_sum[i-1])
    return cumulative_sum

but it can be easily done with itertools.accumulate as follows:

cumulative_sum = list(itertools.accumulate(<list>))

reyadussalahin avatar May 24 '21 05:05 reyadussalahin