Open In App

Python | Chuncked summation every K value

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The prefix array is quite famous in the programming world. This article would discuss a variation of this scheme. To perform a chunked summation where the sum resets at every occurrence of the value K , we need to modify the summation logic. The idea is:

  1. Traverse the list.
  2. Keep adding to the cumulative sum (sm).
  3. If the element is equal to K, reset the sum and continue the accumulation from the next element.

Method #1 : Using Naive Method In the naive method, we just construct the new list comprising of the sum of prev. value of list until K and restarts the procedure once a non K value is encountered. 

Python
# Python3 code to demonstrate
# Chunked summation every K value

# Initializing the list
lst = [1, 2, 0, 3, 4, 0, 5]
K = 0  # The value where sum resets

# Initialize empty list for cumulative sum
ls = []
sm = 0

# Chunked summation using cumulative approach
for i in range(len(lst)):
    if lst[i] == K:
        sm = 0  # Reset sum when we encounter K
    sm += lst[i]  # Add current element to sum
    ls.append(sm)  # Append cumulative sum to the list

# Printing result
print("The computed modified new list:", ls)

Output
The computed modified new list: [1, 3, 0, 3, 7, 0, 5]

Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
 

Method #2 : Using List Comprehension
In List Comprehenson, it creates a new list from an original list by adding each element to the sum of the K-1 previous elements. This is done using a list comprehension and the sum() function. The slice of the original list used to compute the sum starts from the maximum of 0 and i-K+1 to handle the first few elements, and ends at i+1 to include the current element. The new list is then printed.

Python
# Python3 code to demonstrate 
# Chuncked summation every K value
# using list comprehension

# initializing list of lists
test_list = [1, 3, 4, 10, 4, 5, 10, 7, 8]

# initializing K 
K = 10

# printing original list
print ("The original list is : " + str(test_list))

# Chuncked summation every K value using list comprehension
new_list = [sum(test_list[max(0, i-K+1):i+1]) for i in range(len(test_list))]

# printing result
print("The computed modified new list : " + str(new_list))

Output
The original list is : [1, 3, 4, 10, 4, 5, 10, 7, 8]
The computed modified new list : [1, 4, 8, 18, 22, 27, 37, 44, 52]

Time Complexity: O(n*m), where n is the length of the input list and m is the chunk size.
Auxiliary Space: O(n), as we need to create a new list of the same size as the input list 


Next Article
Practice Tags :

Similar Reads