October 13, 2024

Cumulative Sum Program in Python

A cumulative sum (also known as a running total) is the sum of a sequence of numbers that is updated each time a new number is added. For example, given the list [1, 2, 3, 4], the cumulative sum would be [1, 3, 6, 10].

How to Calculate the Cumulative Sum

  1. Initialize an empty list or array to store the cumulative sums.
  2. Iterate through the original list of numbers.
  3. For each number, add it to the running total.
  4. Store the running total in the cumulative sum list.

Python Implementation of Cumulative Sum

def cumulative_sum(numbers):
    cum_sum = []
    running_total = 0

    for number in numbers:
        running_total += number
        cum_sum.append(running_total)

    return cum_sum

# Example usage:
numbers = [1, 2, 3, 4, 5]
result = cumulative_sum(numbers)
print("Cumulative sum:", result)
    

Explanation of the Code

  • cum_sum = []: Initializes an empty list to store the cumulative sums.
  • running_total = 0: Initializes the running total to 0.
  • for number in numbers:: Iterates over each number in the input list.
  • running_total += number: Adds the current number to the running total.
  • cum_sum.append(running_total): Appends the running total to the cumulative sum list.
  • The function returns the list cum_sum, which contains the cumulative sums.

Complexity Analysis

The time complexity of this cumulative sum program is O(n), where n is the number of elements in the input list. This is because the program needs to traverse the list once to compute the cumulative sums.

The space complexity is also O(n), as the program creates a list of the same size as the input list to store the cumulative sums.

Use Cases of Cumulative Sum

  • Financial Analysis: Cumulative sums are used to calculate running totals of profits, expenses, or other financial metrics over time.
  • Data Analysis: Cumulative sums are useful in time series analysis, where they can be used to understand trends and patterns.
  • Game Development: In games, cumulative sums can be used to keep track of scores, health points, or other cumulative metrics.