Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to find the group sum till each K in a list
When you need to find the cumulative sum of elements in groups separated by a specific key value K, you can use a simple iteration approach. This technique sums elements between occurrences of K and includes K itself in the result.
Example
Below is a demonstration of finding group sums separated by key value K ?
my_list = [21, 4, 37, 46, 7, 56, 7, 69, 2, 86, 1]
print("The list is :")
print(my_list)
my_key = 46
print("The key is")
print(my_key)
my_sum = 0
my_result = []
for ele in my_list:
if ele != my_key:
my_sum += ele
else:
my_result.append(my_sum)
my_result.append(ele)
my_sum = 0
my_result.append(my_sum)
print("The resultant list is :")
print(my_result)
The list is : [21, 4, 37, 46, 7, 56, 7, 69, 2, 86, 1] The key is 46 The resultant list is : [62, 46, 228]
How It Works
The algorithm follows these steps:
- Initialize a sum variable to 0 and an empty result list
- Iterate through each element in the input list
- If the element is not equal to the key K, add it to the running sum
- If the element equals K, append the current sum and K to the result, then reset sum to 0
- After the loop, append the final sum to handle remaining elements
Another Example
Let's see how it works with a different key value ?
numbers = [5, 10, 3, 15, 8, 20, 3, 7, 12]
key = 3
print(f"List: {numbers}")
print(f"Key: {key}")
current_sum = 0
result = []
for num in numbers:
if num != key:
current_sum += num
else:
result.append(current_sum)
result.append(num)
current_sum = 0
result.append(current_sum)
print(f"Group sums: {result}")
List: [5, 10, 3, 15, 8, 20, 3, 7, 12] Key: 3 Group sums: [15, 3, 43, 3, 19]
Key Points
- The key value K acts as a separator and appears in the final result
- Elements before each K are summed together
- The final sum after the last K (or if no K exists) is always included
- Time complexity is O(n) where n is the length of the list
Conclusion
This approach efficiently groups and sums list elements separated by a key value K. The algorithm maintains a running sum and resets it whenever the key is encountered, creating distinct groups with their cumulative sums.
Advertisements
